0

im quite new to recoiljs atom and stuff. Assumming i have 2 atoms

timeRangeAtom which determines the time range of the selection

export const timeRangeAtom = atom<Array<string>>({
   key: 'timeRangeAtom',
   default: [
       dayjs().subtract(7, 'day').format(DateFormat),
       dayjs().subtract(1, 'day').format(DateFormat),
       ],
});

filterAtoms which determines the current user selection of all filters ( one of them is timeRange)

export const filterAtom = atom<any>({
   key: 'filterAtom',
   default: {time: [] },
});

Now in my code, whenever user select a date, i will update the timeRangeAtom value. I'm doing this by calling setTime of useRecoilState

  const [time, setTime] = useRecoilState(
    timeRangeAtom,
  );

Now my question is how can i also sync this change to my filterAtom.time whenever timeRangeAtom change ?

One way is i manually setFilterAtom by calling useRecoilState, but it seems quite tedious and duplicate code. So im not sure is there any other ways ?

Jake Lam
  • 3,254
  • 3
  • 25
  • 44

1 Answers1

0

You can create derived state from other atoms using the selector API:

export const filterAtom = selector({
  key: 'filterAtom',
  get: ({get}) => {
    const timeRange = get(timeRangeAtom);
    return {time: [...timeRange]};
  },
});
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • but in my filterAtom i also need to update it frequently, because there are also other value inside. If we use selector is this good, i thought selector mainly for get value only (even though they have set) thanks – Jake Lam Mar 03 '22 at 02:43
  • @JakeLam I can't respond to code you haven't shown. My answer is a response to the information in your question. – jsejcksn Mar 03 '22 at 03:16