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. It allows you to establish error-handling and loading fallbacks at the parental level. The individual component functions similar to how async/await works in Javascript.
- Chain your operations synchroneously
- No useEffect/setState hassle
- No checking for the presence of your data
import { Suspense } from 'react'
import { suspend } from 'suspend-react'
function Post({ id, version = 'v0' }) {
// Results are cached, the function will only execute when dependencies change
// When it does execute it will suspend the component until it has resolved
const { by, title } = suspend(async (/*id, version*/) => {
// Any async task can run in here, fetch requests, parsing, workers, promises, ...
const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`)
return await res.json()
}, [id, version])
// By the time we're here the async data is guaranteed to exist!
return <div>{title} by {by}</div>
}
function App() {
return (
<Suspense fallback={<div>loading...</div>}>
<Post id={10000} />
</Suspense>
)
}Preloading
You can preload your cache with the same cache keys you later read form. The async function can be external (that goes for suspend(fn, [args]) as well), it receives the cache key dependencies as function arguments and in the same order.
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()
}
// You can preload assets, these will be executed and cached immediately
preload(fetchFromHN, [10000, 'v0'])Cache busting
You can remove cached items, either by clearing them all, or by providing cache keys.
import { clear } from 'suspend-react'
// Clear all cached entries
clear()
// Clear a specific entry
clear([10000, 'v0'])Peeking into entries outside of suspense
Peeking into the cache will give you the result immediately or return undefined if it is not present yet.
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.
Recipes
Simple data fetching
Fetching posts from hacker-news: codesandbox
Infinite load on scroll
Fetching HN posts infinitely: codesandbox
Async dependencies
Component A waits for the result of component B: codesandbox