A simple loading strategy for React Suspense based on react-promise-suspense.
Try a simple demo here.
npm install use-asset
Using assets
Each asset you create comes with its own cache. When you request something from it, the arguments that you pass will act as cache-keys. If you request later on using the same keys, it won't have to re-fetch but serves the result that it already knows.
import React, { Suspense } from "react"
import { createAsset } from "use-asset"
const hackerNewsPost = createAsset(async (id) => {
const resp = await fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
return await resp.json()
})
hackerNewsPost.preload(9000)
function Post({ id }) {
const { by, title } = hackerNewsPost.read(id)
return <div>{title} by {by}</div>
}
function App() {
<Suspense fallback={null}>
<Post id={9000} />
</Suspense>
}
Cache busting strategies
const hackerNewsPost = createAsset(fn, 15000)
hackerNewsPost.clear()
hackerNewsPost.clear(9000)
Reading entries outside of suspense
hackerNewsPost.peek(9000)
Using hooks and global cache
You can also use the useAsset
hook, this uses a global cache, anything you request at any time is written into it.
import { useAsset } from "use-asset"
const hackerNewsPost = async (id) => { }
function Post({ id }) {
const { by, title } = useAsset(hackerNewsPost, [id])
return <div>{title} by {by}</div>
}
function App() {
<Suspense fallback={null}>
<Post id={9000} />
Cache busting, preview, multiple arguments, preload and peeking
The hook has the same API as any asset:
useAsset(fn, [9000], 15000)
useAsset.clear()
useAsset.clear(9000)
useAsset.peek(9000)
useAsset.preload(fn, [9000])
useAsset(fn, [1, 2, 3, 4])