Created
January 12, 2021 13:58
-
-
Save Rafe/3b0e152cd6587f8c0366f8e00e6acb7c to your computer and use it in GitHub Desktop.
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
const Unitialized = -1; | |
const Pending = 0; | |
const Resolved = 1; | |
const Rejected = 2; | |
function suspenseFetch(url) { | |
const payload = { | |
_status: Unitialized, | |
_result: () => fetch(url) | |
} | |
return () => { | |
if (payload._status === Uninitialized) { | |
const promise = payload._result() | |
payload._status = Pending | |
payload._result = promise | |
promise.then((res) => { | |
if (payload._status === Pending) { | |
payload._status = Resolved | |
payload._result = res | |
} | |
}, (err) => { | |
if (payload._status === Pending) { | |
payload._status = Rejected | |
payload._result = err | |
} | |
}) | |
} else if (payload._status === Resolved) { | |
return payload._result | |
} else { | |
throw payload._result | |
} | |
} | |
} | |
// in app | |
const fetchUser = suspenseFetch(`/users/1`) | |
const User = () => { | |
const user = fetchUser() | |
return <div>{user.name}</div> | |
} | |
const App = () => ( | |
<Suspense fallback={<h1>Loading user...</h1>}> | |
<User> | |
</Suspense> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment