Created
November 1, 2019 17:42
-
-
Save ilyamkin/c589f3c20ee2d6d031b56f6d21bd8bf1 to your computer and use it in GitHub Desktop.
prefetch-query
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
function wrapPromise(promise) { | |
let status = "pending"; | |
let result; | |
let suspender = promise.then( | |
r => { | |
status = "success"; | |
result = r; | |
}, | |
e => { | |
status = "error"; | |
result = e; | |
} | |
); | |
return { | |
read() { | |
if (status === "pending") { | |
throw suspender; | |
} else if (status === "error") { | |
throw result; | |
} else if (status === "success") { | |
return result; | |
} | |
} | |
}; | |
} | |
// Function that reads resource object | |
// It could also include Cache logic | |
export const usePrefetchedQuery = prefetchedQuery => prefetchedQuery.read(); | |
export const prefetchQuery = (input, init) => { | |
// Make fetch request | |
const promise = fetch(input, init).then(response => response.json()); | |
// Return resource for Suspense | |
return wrapPromise(promise); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment