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. You can chain operations, you do not need to go through the useEffect/setState hassle, you don't need to check for the presence of your data.
import { Suspense } from 'react'
import { suspend } from 'suspend-react'
function Post({ id }) {
// 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, 'v0'])
// 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
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
import { clear } from 'suspend-react'
// Clear all cached entries
clear()
// Clear a specific entry
clear([10000, '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'])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