UNPKG

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

45 lines (44 loc) 1.56 kB
import { useEffect, useState } from "react"; import { useQueryCacheStore } from "./createQueryCacheStore"; export function useQueryZustand(key, fetchFn, options) { const cacheStore = useQueryCacheStore(); const cache = useQueryCacheStore((s) => s.cache[key]); const [data, setData] = useState(cache?.data ?? null); const [error, setError] = useState(cache?.error ?? null); const [isLoading, setIsLoading] = useState(cache?.isLoading ?? false); useEffect(() => { let isMounted = true; if (options?.enabled === false) return; setIsLoading(true); cacheStore .fetchQuery(key, fetchFn, options?.staleTime ?? 0, (err) => { if (isMounted) setError(err); options?.onError?.(err); }, options?.retry) .then((result) => { if (isMounted) setData(result); }) .catch((err) => { if (isMounted) setError(err); }) .finally(() => { if (isMounted) setIsLoading(false); }); return () => { isMounted = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [key, fetchFn, options?.enabled, options?.staleTime, options?.retry]); return { data, error, isLoading, refetch: () => cacheStore.fetchQuery(key, fetchFn, 0, options?.onError, options?.retry), invalidate: () => cacheStore.invalidateQuery(key), }; }