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:
Norbert Maciaszek
2025-08-16 13:42:33 +02:00
parent 03b00ad399
commit 7ecbc55843
3 changed files with 65 additions and 2 deletions

View 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;
};