-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #144 from prgrms-fe-devcourse/143-feature/usefetch…
…-caching Feat: useFetch 캐싱 기능 추가
- Loading branch information
Showing
3 changed files
with
53 additions
and
2 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import { create } from 'zustand'; | ||
|
||
interface Cache { | ||
data: unknown; | ||
timestamp: number; | ||
} | ||
|
||
export const useCacheStore = create<{ | ||
caches: { [url: string]: Cache }; | ||
hasCache: (url: string) => boolean; | ||
registerCache: (url: string, data: unknown) => void; | ||
clear: (url: string) => void; | ||
}>((set, get) => ({ | ||
caches: {}, | ||
hasCache: (url: string) => { | ||
const cache = get().caches[url]; | ||
if (!cache) return false; | ||
const currentTime = Date.now(); | ||
const expirationTime = 5 * 60 * 1000; // 5분 (밀리초 단위) | ||
return currentTime - cache.timestamp < expirationTime; | ||
}, | ||
registerCache: (url: string, data: unknown) => { | ||
if (!get().hasCache(url)) { | ||
set(state => ({ | ||
...state, | ||
caches: { | ||
...state.caches, | ||
[url]: { | ||
data, | ||
timestamp: Date.now(), | ||
}, | ||
}, | ||
})); | ||
} | ||
}, | ||
clear: (url: string) => | ||
set(state => { | ||
const restCaches = { ...state.caches }; | ||
delete restCaches[url]; | ||
return { ...state, caches: restCaches }; | ||
}), | ||
})); |