atom
const categoriesAtom = atom<Category[]>({
key: “categoriesAtom”,
default: [],
});
const itemsAtom = atom<Item[]>({
key: “itemsAtom”,
default: [],
});
selector
const categoriesSelector = selector({
key: “categoriesSelector”,
get: async () => await fetchCategories(),
});
const itemsSelector = selector({
key: “itemsSelector”,
get: async () => await fetchItems(),
});
hook
const useGetCategories = () => {
const [categories, setCategories] = useRecoilState(categoriesAtom);
const { state, contents } = useRecoilValueLoadable(categoriesSelector);
const refresher = useRecoilRefresher_UNSTABLE(categoriesSelector);
React.useEffect(() => {
switch (state) {
case “hasValue”:
setCategories(contents);
break;
case “hasError”:
// error handling
break;
case “loading”:
// loading
break;
default:
break;
}
return () => {
setCategories([]);
refresher();
};
}, [state]);
return state;
};
const useGetItems = () => {
const [items, setItems] = useRecoilState(itemsAtom);
const { state, contents } = useRecoilValueLoadable(itemsSelector);
const refresher = useRecoilRefresher_UNSTABLE(itemsSelector);
React.useEffect(() => {
switch (state) {
case “hasValue”:
setItems(contents);
break;
case “hasError”:
// error handling
break;
case “loading”:
// loading
break;
default:
break;
}
return () => {
setItems([]);
refresher();
};
}, [state]);
return state;
};