Add SWR for data fetching and implement useSWRStorage hook: update package.json and package-lock.json to include SWR dependency, and create a custom hook for managing localStorage with SWR for improved data persistence.
This commit is contained in:
30
src/hooks/useSWRStorage/index.ts
Normal file
30
src/hooks/useSWRStorage/index.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { useEffect } from "react";
|
||||
import useSWR, { SWRConfiguration } from "swr";
|
||||
|
||||
export const useSWRStorage = (
|
||||
key: string,
|
||||
fetcher: (key: string) => Promise<any>,
|
||||
options: SWRConfiguration = {}
|
||||
) => {
|
||||
let fallbackData =
|
||||
typeof window !== "undefined" &&
|
||||
JSON.parse(localStorage.getItem(key) || "null");
|
||||
|
||||
if (!fallbackData) {
|
||||
fallbackData = options.fallbackData;
|
||||
}
|
||||
|
||||
const res = useSWR(key, fetcher, {
|
||||
revalidateOnFocus: false,
|
||||
...options,
|
||||
fallbackData,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (res.data) {
|
||||
localStorage.setItem(key, JSON.stringify(res.data));
|
||||
}
|
||||
}, [res.data]);
|
||||
|
||||
return res;
|
||||
};
|
||||
Reference in New Issue
Block a user