Package Exports
- suspend-react
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (suspend-react) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
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.
Preloading
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'])Cache busting
import { clear } from 'suspend-react'
// Clear all cached entries
clear()
// Clear a specific entry
clear([1000, 'v0'])Peeking into entries outside of suspense
import { peek } from 'suspend-react'
// This will either return the value (without suspense!) or undefined
peek([1000, 'v0'])Typescript
Correct types will be inferred automatically.
React 18
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.
Demos
Fetching posts from hacker-news: codesandbox