Read Data

Learn how to read data (i.e. blog posts) from the Firestore database.

Read data from the Firestore database

The default Sapper template already comes with a basic blog page. The individual blog posts are persisted in services/web/src/routes/blog/_posts.js. Instead, we want to load blog posts from the Firestore database. We are going to start with the src/routes/blog/index.svelte page.

Fetch from the database using Sapper’s prefetching

There are two <script> elements. The first one, with context="module", contains a preload function. This is a Sapper feature used to prefetch data before the page is loaded. The preload function is either called on the server if the user accesses the given page directly (e.g. through a bookmark or a link clicked on a different website), or it is called to the client before the page displays. You can see this in action if you open the homepage and look at the developer tools’ Network tab. While on the homepage, move your mouse over the blog navigation item, but don’t click. As soon as your mouse is over the blog link, you will notice requests in the Network tab. That’s Sapper prefetching the /blog URL! By the time you click the link, the page is instantly rendered.

We can take advantage of that and fetch the blog posts from the database when a user moves their mouse over the blog link. That gives us a tiny bit of a head start to fetch and render the blog posts. We can replace the body of the preload function with this:

if (typeof window !== "undefined") {
  return window.db
    .collection("posts")
    .get()
    .then(querySnapshot => {
      const posts = querySnapshot.docs.map(doc => ({
        slug: doc.id,
        ...doc.data()
      }));
      return {
        posts
      };
    });
}
return null;

Get hands-on with 1200+ tech skills courses.