Qwik emote

Qwik Framework

Fetch Data with 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.

2023-08-12
5 min read
Difficulty
qwik
Qwik emote

TOPICS

What is 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$ example

Router 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.

QwikTypeScript
Router Loader example
export const useNews = routeLoader$(async () => {
  const res = await fetch('api/news');
  const users = await res.json();
  return users as User[];
});
QwikTypeScript
Usage
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 }/>
    </>
  );
});

Rules

Some rules:

  • So, as we said, they must be declared in layout tsx or index tsx
  • a routerLoader can be used to get data from a database, by using a REST API, ORM (o er em) or SDK (es di key)
  • Since they run on server they can cointains secret data such as API KEYS, TOKEN and so on and they won't be exposed on the client
  • You can define multiple routerLoader in a file, and the page won't be rendered until all are completed
  • Data can be consumed by any Qwik Component

How it works

So let's see how it works:

  • We can declare one or more routerLoaders in index or layout tsx files
  • Any component can consume them
  • the routerLoader$ function is invoked on server...
  • ...that can fetch data in several ways
  • and the page (and its children) is rendered on server

Animated Demo

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.

Video Tutorial

This content is also available as video tutorial:

Follow me for more tips

Follow me on my YouTube Channel or on LinkedIn for more tips and tutorials about front-end topics

Keep updated about latest content
videos, articles, tips and news