Render as you Fetch

Render as you Fetch is a pattern that lets you start fetching the data you will need at the same time you start rendering the component using that data. This way you don't need to wait to render in the loading state to start fetching, called Fetch-on-Render, neither wait for fetching to finish to start rendering, called Fetch-Then-Render.

You could render a component that will read the data:

import { useResource } from 'coreql';
function User({ id }) {
const { data: user } = useResource('users', id);
return <h1>{user?.data.attributes.fullName}</h1>;
}
export default User;

Then in a parent component render our component and start to prefetch the data at the same time.

import { useQueryCache } from 'react-query';
import { getResourceKey, getResource } from 'coreql';
function App() {
const [id, setId] = React.useState(1);
const queryCache = useQueryCache();
function handleChange(event) {
// this trigger the prefetch
queryCache.prefetchQueries(
getResourceKey(['users', event.target.value]),
getResource,
);
setId(event.target.value); // this trigger the render
}
return (
<>
<input type="text" value={id} onChange={handleChange} />
<ErrorBoundary fallback={<p>Error</p>}>
<React.Suspense fallback={<p>Loading...</p>}>
<User id={id} />
</React.Suspense>
</ErrorBoundary>
</>
);
}

Now you will start rendering as soon as you trigger the render, which means you don't need to wait for the loading state to happen to start fetching neither finish the fetch to start rendering.