Next Js Use Data
Last active
December 1, 2021 22:18
-
-
Save GGrassiant/b5243e711e64029c862dd25f0222b884 to your computer and use it in GitHub Desktop.
Next Js Use Data
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
export default async function fetchData(type) { | |
const res = await fetch(`https://hacker-news.firebaseio.com/v0/${type}.json`); | |
if (res.status !== 200) { | |
throw new Error(`Status ${res.status}`); | |
} | |
return res.json(); | |
} |
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
const cache = {}; | |
export default function useData(key, fetcher) { | |
if (!cache[key]) { | |
let data; | |
let promise; | |
cache[key] = () => { | |
if (data !== undefined) return data; | |
if (!promise) promise = fetcher().then((r) => (data = r)); | |
throw promise; | |
} | |
} | |
return cache[key](); | |
} | |
// used like: const storyIds = useData('top', () => fetchData('topstories')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment