Skip to content

Instantly share code, notes, and snippets.

@ilyamkin
Created November 1, 2019 17:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilyamkin/c589f3c20ee2d6d031b56f6d21bd8bf1 to your computer and use it in GitHub Desktop.
Save ilyamkin/c589f3c20ee2d6d031b56f6d21bd8bf1 to your computer and use it in GitHub Desktop.
prefetch-query
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