@daveyplate/supabase-swr-entities
Version:
An entity management library for Supabase and SWR
31 lines (30 loc) • 1.03 kB
JavaScript
import { useCallback } from "react";
import useSWR from "swr";
import useSWRInfinite from 'swr/infinite';
import { useAPI } from "./api-methods";
/**
* Wraps useSWR with custom fetcher and getKey
*/
export function useInfiniteCache(url, config) {
const { getAPI } = useAPI();
const getKey = useCallback((pageIndex, previousPageData) => {
if (!url)
return null;
// reached the end
if (previousPageData && !previousPageData.data)
return null;
// first page, we don't have `previousPageData`
if (pageIndex === 0)
return url;
const { limit } = previousPageData;
// add the cursor to the API endpoint
return url + `&offset=${pageIndex * limit}`;
}, [url]);
const swr = useSWRInfinite(getKey, Object.assign({ fetcher: getAPI }, config));
return swr;
}
export function useCache(url, config) {
const { getAPI } = useAPI();
const swr = useSWR(url, Object.assign({ fetcher: getAPI }, config));
return swr;
}