Skip to content

Instantly share code, notes, and snippets.

@julianburr
Last active January 20, 2019 12:17
Show Gist options
  • Save julianburr/f19683b791c4ce2aa2509edc530ef77e to your computer and use it in GitHub Desktop.
Save julianburr/f19683b791c4ce2aa2509edc530ef77e to your computer and use it in GitHub Desktop.
Why Suspense Will Be a Game Changer - Dumbest Cache Provider Example
// Yep, we're doing it, just storing the data on a plain old object
let data = {};
export default (fetchFn, getKey = (x) => x) => (args) => {
// Get unique identifier from arguments
const key = getKey(args);
if (data[key]) {
if (typeof data[key].then === 'function') {
// Fetch has already been triggered
// So throw the stored promise instead of triggering another request
throw data[key];
}
// Return already loaded data!
return data[key];
}
// Nothing loaded yet, so trigger the given fetch method
// with the given arguments and throw the resulting promise
const promise = fetchFn(args).then((response) => {
// Store response in cache, so on re-render its available
data[key] = response;
return response;
});
// Throw promise to suspend rendering
data[key] = promise;
throw promise;
};
// ---------------------------------
// Example usage
// ---------------------------------
const fetchPokemon = createFetcher((index) =>
fetch(`https://pokeapi.co/api/v2/pokemon/${index}`).then((data) =>
data.json()
)
);
function HallOfFame () {
return (
<Suspense fallback={<p>Loading...</p>}>
<h1>Magikarp</h1>
{/* This is not a magic number, YOU SHOULD KNOW THESE ;) */}
<Pokemon index={129} />
<h1>Caterpie</h1>
<Pokemon index={10} />
</Suspense>
);
}
function Pokemon (props) {
const data = fetchPokemon(props.index);
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment