我正在向服务器发出请求以根据搜索字符串搜索学生。我从那里得到结果,selectorFamily
但我也希望能够将这些结果存储在其中,studentsAtom
这样我就不必再次提出请求,并且可以在其他地方使用该状态。
我该怎么做呢?
我的反冲代码:
// 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);
},
});
我的组件中的代码:
const studentSearchQuery = useRecoilValue(
studentSearchQuerySelector(searchString)
);