Search code examples
reactjsrecoiljs

How to I store the results of a query using react recoil selectorFamily?


I am making a request to the server to search for students based on a search string. I get the results back from the selectorFamily but I also want to be able to store those results in the studentsAtom so I don't have to make the request again, and I can use the state in other places.

How do I do this?

My recoil code:

// Map of all students, indexed by id
// e.g { 45: 'Bruce', 89: 'Alice }
export const studentsAtom = atom({
  key: "students",
  default: {}
}

// Make a request to the backend to search by student name
// e.g. searchStudents('Bru') will return Search: ['Bruce']
export const studentSearchQuerySelector = selectorFamily({
  key: "studentSearch",
  get: (searchString: string) => async ({ get }) => {

    const response = await searchStudents(searchString);
    if (response.ok) {
      return response.json();
    }

    throw new Error(response.statusText);
  },
});

The code within my component:

const studentSearchQuery = useRecoilValue(
   studentSearchQuerySelector(searchString)
);

Solution

  • try,

      const studentAtomFamily = atomFamily({
      key: "students",
      default: selectorFamily({
        key: 'studentSearch',
        get: searchString => async ({get}) => {
          const response = await searchStudents(searchString)
          if (response.ok) return response.json()
          throw new Error(response.statusText)
        },
      }),
    });