Skip to content

Commit

Permalink
v1.4.0
Browse files Browse the repository at this point in the history
  • Loading branch information
vitorbertolucci committed Dec 10, 2020
1 parent d4906f6 commit 5c24b8b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-cached-fetch",
"version": "1.3.0",
"version": "1.4.0",
"description": "React hook for fetching data with cache functionality",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
50 changes: 48 additions & 2 deletions src/cachedFetchProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import React, { useCallback, useState, useMemo, createContext } from 'react';
import React, {
useCallback,
useState,
useMemo,
createContext,
useEffect,
} from 'react';

export interface IHeaderOptions {
[key: string]: string;
}

type IPersistenceType = 'none' | 'session' | 'local';

interface ICachedFetchGlobalOptions {
headers: IHeaderOptions;
fetcher: (route: string, headers: IHeaderOptions) => Promise<any>;
Expand All @@ -20,6 +28,8 @@ interface ICachedFetchProviderGlobalOptions {

interface ICachedFetchProviderProps {
globalOptions?: ICachedFetchProviderGlobalOptions;
persistence?: IPersistenceType;
persistencePrefix?: string;
}

interface ICache {
Expand Down Expand Up @@ -55,9 +65,32 @@ const defaultOptions: ICachedFetchGlobalOptions = {

export const CachedFetchProvider: React.FC<ICachedFetchProviderProps> = ({
globalOptions,
persistence = 'none',
persistencePrefix,
children,
}) => {
const [cache, setCache] = useState<ICache>({});
const [cache, setCache] = useState<ICache>(() => {
if (persistence === 'none') {
return {};
}

if (!persistencePrefix) {
throw new Error(
'persistencePrefix must be provided when persistence is set to session or local',
);
}

const storage = persistence === 'session' ? sessionStorage : localStorage;

const persistedCache = storage.getItem(
`${persistencePrefix}-react-cached-fetch`,
);
if (!persistedCache) {
return {};
}

return JSON.parse(persistedCache);
});

const updateCache = useCallback((key, data) => {
setCache((current: ICache) => ({ ...current, [key]: data }));
Expand All @@ -71,6 +104,19 @@ export const CachedFetchProvider: React.FC<ICachedFetchProviderProps> = ({
return { ...defaultOptions, ...globalOptions };
}, [globalOptions]);

useEffect(() => {
if (persistence === 'none' || !persistencePrefix) {
return;
}

const storage = persistence === 'session' ? sessionStorage : localStorage;

storage.setItem(
`${persistencePrefix}-react-cached-fetch`,
JSON.stringify(cache),
);
}, [persistence, persistencePrefix, cache]);

return (
<CachedFetchContext.Provider
value={{
Expand Down

0 comments on commit 5c24b8b

Please sign in to comment.