Endpoint Expiry Policy
By default, Reactive Data Client uses stale-while-revalidate. When data is available, components render it immediately. If the data is old enough, Data Client refetches it in the background.
Expiry status
dataExpiryLengthHow long (in milliseconds) a response stays fresh before it becomes stale. Learn moreFresh
The data is new enough. Data Client does not fetch it.
dataExpiryLengthOnce dataExpiryLength (in milliseconds) has passed, the cached response is stale: still shown, but refetched. Learn moreStale
Components can show the data. Data Client fetches it again when a component needs it.
ctrl.invalidate()Marks the data invalid right away, even while fresh, so components that need it fetch again. Learn moreInvalid
Components cannot show the data. A component that needs it fetches it and suspends. If no component needs the data, nothing happens.
useSuspense() checks the data on mount and when its parameters change. It fetches if the data is stale.
When using React Navigation, focus events also trigger fetches for stale data.
Expiry Time
Endpoint.dataExpiryLength
Endpoint.dataExpiryLength sets how many milliseconds data stays
'fresh' before it becomes 'stale'. Set it to a low number like 50 to make data
stale almost immediately, or to a large number to keep it fresh for a long time.
Toggling between 'first' and 'second' changes the parameters. While the data is fresh, the old time stays without a refetch.
import { lastUpdated } from './api/lastUpdated'; export const getUpdated = lastUpdated.extend({ dataExpiryLength: 10000 });
@data-client/rest
Long cache lifetime
import {
RestEndpoint,
RestGenerics,
resource,
} from '@data-client/rest';
// We can now use LongLivingEndpoint to create endpoints that will be cached for one hour
class LongLivingEndpoint<
O extends RestGenerics,
> extends RestEndpoint<O> {
dataExpiryLength = 60 * 60 * 1000; // one hour
}
const LongLivingResource = resource({
path: '/:id',
Endpoint: LongLivingEndpoint,
});
Never retry on error
import {
RestEndpoint,
RestGenerics,
resource,
} from '@data-client/rest';
// We can now use NoRetryEndpoint to create endpoints that will be cached for one hour
class NoRetryEndpoint<
O extends RestGenerics,
> extends RestEndpoint<O> {
errorExpiryLength = Infinity;
}
const NoRetryResource = resource({
path: '/:id',
Endpoint: NoRetryEndpoint,
});
Endpoint.invalidIfStale
Endpoint.invalidIfStale eliminates the 'stale' status, making data that expires immediately be considered 'invalid'.
This is demonstrated by the page suspending once its data goes stale (navigation waits on the progress bar). While the data is fresh, the page shows it.
import { lastUpdated } from './api/lastUpdated'; export const getUpdated = lastUpdated.extend({ invalidIfStale: true, dataExpiryLength: 5000, });
Force refresh
To fetch new data while you show the old data:
A specific endpoint
Controller.fetch fetches while components show the previous data. It fetches even when the data is 'fresh'.
import { useSuspense, useController } from '@data-client/react'; import { lastUpdated } from './api/lastUpdated'; function ShowTime() { const { updatedAt } = useSuspense(lastUpdated, { id: '1' }); const ctrl = useController(); return ( <> <div className="listItem"> <span className="meta">API time</span> <time>{updatedAt.toLocaleString('en-US', { timeStyle: 'long' })}</time> </div> <button onClick={() => ctrl.fetch(lastUpdated, { id: '1' })}> Refresh </button> </> ); } render(<ShowTime />);
Refresh visible endpoints
Controller.expireAll() sets all responses' expiry status matching testKey to Stale.
import { useController } from '@data-client/react'; import { lastUpdated } from './api/lastUpdated'; import TimeList from './TimeList'; function Demo() { const ctrl = useController(); return ( <div> <TimeList /> <div className="buttonGroup"> <button onClick={() => ctrl.expireAll(lastUpdated)}> Expire All </button> <button onClick={() => ctrl.fetch(lastUpdated, { id: '1' })}> Force Refresh First </button> </div> </div> ); } render(<Demo />);
Invalidate (re-suspend)
Both endpoints and entities can be invalidated.
A specific endpoint
In this example invalidating the endpoint shows the loading fallback since the data is not allowed to be displayed.
import { useController } from '@data-client/react'; import { lastUpdated } from './api/lastUpdated'; import TimeList from './TimeList'; function Demo() { const ctrl = useController(); return ( <div> <TimeList /> <div className="buttonGroup"> <button onClick={() => ctrl.invalidateAll(lastUpdated)}> Invalidate All </button> <button onClick={() => ctrl.invalidate(lastUpdated, { id: '1' })}> Invalidate First </button> </div> </div> ); } render(<Demo />);
Any endpoint with an entity
The Invalidate schema invalidates every endpoint whose response includes that entity. If the endpoint has the entity in an Array, Data Client removes it from that Array.
import { useController, useLoading } from '@data-client/react'; import { InvalidateTimedEntity, deleteLastUpdated, } from './api/lastUpdated'; import ServerTime from './ServerTime'; function ShowTime() { const ctrl = useController(); const [handleDelete, loadingDelete] = useLoading( () => ctrl.fetch(deleteLastUpdated, { id: '1' }), [], ); return ( <div> <ServerTime id="1" /> <div className="buttonGroup"> <button onClick={handleDelete} aria-busy={loadingDelete}> Invalidate </button> <button onClick={() => ctrl.setResponse(deleteLastUpdated, { id: '1' }, { id: '1' }) } > Invalidate (without fetching DELETE) </button> <button onClick={() => ctrl.set([InvalidateTimedEntity], [{ id: '1' }])} > Invalidate Entity with ctrl.set </button> </div> </div> ); } render(<ShowTime />);
Controller.fetch() updates the server and the store. To change only the store, use Controller.setResponse() or Controller.set().
Conditional Invalidation based on data
To invalidate only for some responses, return undefined from Entity.process.
class PriceLevel extends Entity {
price = 0;
amount = 0;
pk() {
return this.price;
}
static process(
input: [number, number],
parent: any,
key: string | undefined,
): any {
const [price, amount] = input;
if (amount === 0) return undefined;
return { price, amount };
}
}