15. Next.js Tutorial (2). Fetching data. Async functions getStaticProps, getServerSideProps, getStaticPaths

 1. Fetching data at the beginning of the application

In the index.tsx (index.ts) you can use one of these 2 asyncfunctions:

  • getStaticProps()  which works in client-side pre-rendering and the content is reused. So only one call is made, and it is made at build time. This is quicker.
  • getServerSideProps() that works on the server-side rendering and every call can produce different results as data changes. Use only if you need to render a page whose data must be fetched at request time such as authorization.

//export async function getStaticProps() {    // only on pre-rendering
export async function getServerSideProps() {  // only on server side rendering
  const allPostsData = getSortedPostsData();
  return {
    props: {
      allPostsData,
    },
  };
  
}

export default function Home({allPostsData}:{allPostsData: PostData[]}) {
  return (
    <Layout home>
.......
Do not use API route inside getServerSideProps, insted use the logic of calling the CMS, database or other source of data from getServerSideProp

2. Using SWR for fetching data

You can use the SWR hook to fetch data as shows this example

import React from "react";
import useSWR from "swr";

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function App() {
  const { data, error, isLoading } = useSWR(
    "https://api.github.com/repos/vercel/swr",
    fetcher
  );

  if (error) return "An error has occurred.";
  if (isLoading) return "Loading...";
  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
      <strong> {data.subscribers_count}</strong>
    </div>
  );
}

And using a browser and going to "https://api.github.com/repos/vercel/swr"  you can see this json code:

{
  "id": 218115303,
  "name": "swr",
  "description": "React Hooks for Data Fetching",
  "subscribers_count": 195,
  ......
}

And the output is 






Comentarios

Entradas populares de este blog

14. Next.js Tutorial (1)

18. Next.js Tutorial (5). Deploying. HTTPS