Skip to content

Instantly share code, notes, and snippets.

@occar421
Created July 24, 2022 15:34
Show Gist options
  • Save occar421/7071fb8777c40122cbe0caf4780059f9 to your computer and use it in GitHub Desktop.
Save occar421/7071fb8777c40122cbe0caf4780059f9 to your computer and use it in GitHub Desktop.
const { data } = useQuery(["pets", 1], fetch(`/pets`), { map: (v) => v });
const useQuery = (key, fetcher, { map }) => {
const [payload, setPayload] = useRecoilState(cacheState(key));
const promise = payload ? Promise.resolve() : fetcher().then(setPayload);
const data = useMemo(
() => (payload ? map(payload) : undefined),
[map, payload]
);
if (!payload) {
throw promise;
}
return { data };
};
const useQueries = (queries) => {
const statePair = useRecoilState(allCachesState(queries.map((q) => q.key)));
const promise = Promise.all(
statePair.map((p) => (p[0] ? Promise.resolve() : fetcher().then(p[1])))
);
/// omit
};
const cacheState = atomFamily({
key: "cacheState",
});
const allCachesState = selector({
key: "allCachesState",
get:
({ get }) =>
(keys) =>
keys.map((key) => get(cacheState(key))),
set: ({ set }, { keys, value }) => {
for (const key in keys) {
set(allCachesAtom(key), value);
}
},
});
const useQueryClient = (key) => {
const set = useSetRecoilState(allCachesSelector);
return {
invalidateQueries: (keys) => {
set(keys, undefined);
},
};
};
@occar421
Copy link
Author

occar421 commented Jul 31, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment