routerLoader$
?A Router Loader is a strategy available in Qwik to execute async operation, for example to fetch data in the server and to consume them in any Qwik component.
routerLoader$
exampleRouter Loaders can only be declared in the /routes
folder, in the layout.tsx
file or in index.
tsx files and they are triggered after a route change, so when users visit the page where they are used.
In this example you can see how we define a routerLoader$
that is simply a function that fetch and return some data.
Any Qwik component, even children, can then import and use a routeLoader$
, they will be automatically invoked when the page that contains them is mount.
Anyway the whole page will be rendered only when all async operations are completed.
export const useNews = routeLoader$(async () => {
const res = await fetch('api/news');
const users = await res.json();
return users as User[];
});
export default component$( () => {
const news = useNews();
const projects = useProjects();
const photos = usePhotos();
return (
<>
<Information />
<News data={news.value} />
<Projects data={projects.value} />
<Photos photo={photos.value }/>
</>
);
});
Some rules:
So let's see how it works:
routerLoader$
function is invoked on server...So a component can consume mulitiple router loaders, all data is fetched on server and the page is rendered only when all loaders are completed.
This content is also available as video tutorial:
Follow me on my YouTube Channel or on LinkedIn for more tips and tutorials about front-end topics