The async function that will be called when suspending. It will accept the key
parameter.
If you don't need a key
, you can use bindSuspense instead.
The cache key
Optional
storage?: Storage(Advanced) You can provide the backing cache object
Access to the backing cache.
Useful for doing cache.set(key, null)
, and force a re-fetch.
Suspend your tree while the async function resolves, it takes a key
, and return its promise's value
The key can be any type, as it is passed directly to Map
(by default).
It can be a good idea to customize your storage
to avoid memory leaks (with WeakMap
) if your keys are always objects,
or to allow for more complex cache invalidation logic (e.g. with quick-lru
).
If you need multiple objects as your key (e.g. { userId, postId }
), you can use JSON.stringify
to convert it to a string,
or pass them as an array and use a many-keys-map
as your storage
.
import { bindKeyedSuspense } from "@cprecioso/react-suspense";
const userData = bindKeyedSuspense((userId) =>
fetch(`/api/user/${userId}`).then((res) => res.json())
);
export const UserInfo = ({ userId }) => {
const { name } = userData.suspend(userId);
return <p>Name: {name}</p>;
};
import { bindKeyedSuspense } from "@cprecioso/react-suspense";
import ManyKeysMap from "many-keys-map";
const postData = bindKeyedSuspense(
([userId, postId]) =>
fetch(`/api/post/${userId}/${postId}`).then((res) => res.json()),
{ storage: new ManyKeysMap() }
);
export const PostInfo = ({ userId, postId }) => {
const {
title,
author: { name },
} = postData.suspend([userId, postId]);
return (
<p>
{title}, by {name}
</p>
);
};
Generated using TypeDoc
Create a suspending function that will cache the result of the function call. This function will be called only once, with the key as its arguments, and the result will be cached for that key.