npm install suspend-reactThis library integrates your async ops into React suspense. Error-handling & loading states are handled at the parental level. The individual component functions similar to async/await in Javascript.
- Chain your operations synchronously
- No useEffect/setState hassle
- No checking for the presence of your data
- All React versions >= 16.6
import { Suspense } from 'react'
import { suspend } from 'suspend-react'
function Post({ id, version = 'v0' }) {
const { by, title } = suspend(async (/*id, version*/) => {
const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`)
return await res.json()
}, [id, version])
return <div>{title} by {by}</div>
}
function App() {
return (
<Suspense fallback={<div>loading...</div>}>
<Post id={1000} />
</Suspense>
)
}What happened here?
- You have a promise, stick it into the
suspendfunction. It will interupt the component. - The component needs to be wrapped into
<Suspense fallback={...}>which allows you to set a fallback. - If
suspendruns again with the same dependencies it will return the cached result.
import { preload } from 'suspend-react'
async function fetchFromHN(id, version) {
const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`)
return await res.json()
}
preload(fetchFromHN, [1000, 'v0'])import { clear } from 'suspend-react'
// Clear all cached entries
clear()
// Clear a specific entry
clear([1000, 'v0'])import { peek } from 'suspend-react'
// This will either return the value (without suspense!) or undefined
peek([1000, 'v0'])Correct types will be inferred automatically.
Suspense, as is, has been a stable part of React since 16.6, but React will likely add some interesting caching and cache busting APIs that could allow you to define cache boundaries declaratively. Expect these to be work for suspend-react once they come out.
Fetching posts from hacker-news: codesandbox