Last active
November 1, 2018 01:10
-
-
Save quisido/7c967a4bcb374fca0e69507fcfd9a9f5 to your computer and use it in GitHub Desktop.
React Suspense with the Fetch API
This file contains hidden or 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
| // 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