Skip to content

Instantly share code, notes, and snippets.

@quisido
Last active November 1, 2018 01:10
Show Gist options
  • Save quisido/7c967a4bcb374fca0e69507fcfd9a9f5 to your computer and use it in GitHub Desktop.
Save quisido/7c967a4bcb374fca0e69507fcfd9a9f5 to your computer and use it in GitHub Desktop.
React Suspense with the Fetch API
// NEW: lifespan parameter
const useFetch = (
input: RequestInfo,
init?: RequestInit | undefined,
lifespan: number = 0
) => {
// ...
const fetchCache: FetchCache = {
fetch:
// Make the fetch request.
fetch(input, init)
.then( /* ... */ )
.then( /* ... */ )
.catch( /* ... */ )
// Invalidate the cache.
.then(() => {
// If the user defined a lifespan,
if (lifespan > 0) {
// Wait for the duration of the lifespan,
setTimeout(
() => {
// Find this fetch request and kill it
// from the memoization array.
const index = fetchCaches.indexOf(fetchCache);
if(index !== -1) {
fetchCaches.splice(index, 1);
}
},
lifespan
);
}
}),
// ...
};
// ...
};
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment