A simple loading strategy for react suspense based on react-promise-suspense.
npm install use-asset
Using assets
use-asset
allows you to create single assets, which bring their own cache. This is great for preload and cache busting.
import React, { Suspense } from "react"
import { createAsset } from "use-asset"
const hackerNewsPost = createAsset(async (res, rej, id) => {
const res = await fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
const json = await res.json()
res(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(..., 15000)
hackerNewsPost.clear()
hackerNewsPost.clear(9000)
Reading entries outside of suspense
hackerNewsPost.peek(9000)
Using hooks and global cache
You can opt into use our hook, useAsset
, this opens up a global cache, anything you request at any time is written into it.
import { useAsset } from "use-asset"
const hackerNewsPost = async (res, rej, id) => {
const res = await fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
const json = await res.json()
res(json)
}
function Post({ id }) {
const { by, title } = useAsset(hackerNewsPost, [id])
return <div>{title} by {by}</div>
}
function App() {
<Suspense fallback={null}>
<Post id={9000}>
</Suspense>
}
Cache busting and peeking
It has the same api
useAsset.clear()
useAsset.clear(9000)
useAsset.peek(9000)