zstoreq
Version:
zustand-query is a library that helps you to query You can cal your api and get the data and store it in zustand store
71 lines (70 loc) • 2.35 kB
JavaScript
import { create } from "zustand";
import { handleError } from "./errorHandler";
export const useQueryCacheStore = create((set, get) => ({
cache: {},
fetchQuery: async (key, fetchFn, staleTime = 0, onError, retry = 0) => {
const existing = get().cache[key];
const now = Date.now();
const isStale = !existing?.lastFetched || now - existing.lastFetched > staleTime;
if (existing && !isStale && existing.data)
return existing.data;
set((state) => ({
cache: {
...state.cache,
[key]: {
...existing,
isLoading: true,
error: null,
fetchFn,
},
},
}));
const attemptFetch = async (retries) => {
try {
const data = await fetchFn();
set((state) => ({
cache: {
...state.cache,
[key]: {
data,
isLoading: false,
error: null,
lastFetched: Date.now(),
fetchFn,
},
},
}));
return data;
}
catch (error) {
if (retries > 0) {
return attemptFetch(retries - 1);
}
handleError(error);
onError?.(error);
set((state) => ({
cache: {
...state.cache,
[key]: {
data: null,
isLoading: false,
error,
lastFetched: Date.now(),
fetchFn,
},
},
}));
throw error;
}
};
return attemptFetch(typeof retry === "number" ? retry : retry ? 3 : 0);
},
invalidateQuery: (key) => {
set((state) => {
const newCache = { ...state.cache };
delete newCache[key];
return { cache: newCache };
});
},
invalidateAll: () => set({ cache: {} }),
}));