如何使用反应后坐力选择器家族存储查询结果?



我正在向服务器发出请求,以根据搜索字符串搜索学生。 我从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)
);

尝试,

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)
},
}),
});

相关内容

  • 没有找到相关文章

最新更新