Prefetching Data before Render
Render as you Fetch is a better pattern and you should use it when possible.
As mentioned in API Client, the hooks are the recommended way to read data in a React component, however, you could combine it with the API Client to give a better UX avoiding loading spinners.
We need to have at least two components, one using the hooks to read data and another one controlling when the first one is rendered. Before we trigger a state change to render the component using the hooks we could use the API Client to fetch the data we know our component will need, this data will fill the cache of the hook, then we change the state and render our component using the hook, this one could read the data we have already fetched and render immediately without showing spinners.
import * as React from 'react';import { useQueryCache } from 'react-query';import { api, useResource, getResourceKey, getResource } from 'coreql';
function Resource({ id }) { // The hook here will read the data previously fetched by the API Client or fetch it if it's not cached yet const { data: resource } = useResource('resource-name', id);
return <p>{resource?.data.attributes.text}</p>;}
function App() { const [showResource, setShowResource] = React.useState(false); const queryCache = useQueryCache();
async function handleShowClick() { // this fetch the data and fill the cache await queryCache.prefetchQuery(getResourceKey('resource-name', 1), getResource); setShowResource(true); }
return ( <> <button onClick={handleShowClick}>Show</button> {showResource && <Resource id={1} />} </> );}This may not be the case all the time since you don't always know what data you will need in the future or that data requires a lot of requests in a waterfall, in that case, it's better to rely on spinners to show you are still loading the data.