Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Last active December 1, 2021 22:18
Show Gist options
  • Save GGrassiant/b5243e711e64029c862dd25f0222b884 to your computer and use it in GitHub Desktop.
Save GGrassiant/b5243e711e64029c862dd25f0222b884 to your computer and use it in GitHub Desktop.
Next Js Use Data
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();
}
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