Boost Your Nextjs Skills : Learn How I Mastered Data Fetching with the Fakestore API

Boost Your Nextjs Skills : Learn How I Mastered Data Fetching with the Fakestore API

Modern frontend experiences are built on the foundation of dynamic web development, which allows data to be fetched with ease and displayed from a variety of sources.

'Learning data fetching can be likened to ordering food from a restaurant. Imagine walking to a restaurant and you send a request to the kitchen for a specific dish, in data fetching, you send a request to an API or database for specific information. The response you receive from the kitchen is like the data you get back from the API. If the kitchen successfully prepares the dish, you enjoy a satisfying meal – similarly, if the data fetch is successful, you can use the obtained information to create a rich and engaging user experience on your website. Just as you might customize your food order, in data fetching, you can tailor your requests to get the exact data you need for your application.'

In this article we will delve deep into Data fetching in NextJs, exploring methods and practical implementation by fetching data from the dummy fakestoreApi.

All the code written in this tutorial is available on Github Repo

What is Data Fetching

Data fetching is the process of obtaining information from outside sources—like databases or APIs—and displaying it on a user interface. The interactive features and real-time updates that users experience from contemporary websites are supported by this process.

Methods of Data Fetching in Next.js

Next.js offers a range of data fetching techniques that cater to different use cases:

  1. Fetching on the Server with fetch: Leveraging the 'fetch' API, you can retrieve data directly on the server-side during initial rendering. By employing data fetching on the server side, the fetch API actively communicates with the server, retrieving the required data even before the webpage reaches your screen. This ensures that your page is preloaded with relevant data before reaching the client, enhancing performance and SEO.

  2. Server-side Data Fetching with Third-party Libraries: Next.js seamlessly integrates with third-party libraries like 'axios' or 'swr' for server-side data fetching. These libraries provide additional features, such as caching and revalidation, further optimizing data retrieval.

  3. Client-side Data Fetching via a Route Handler: For scenarios where data needs to be fetched after the initial render, Next.js allows you to fetch data on the client side. This approach is suitable for scenarios where real-time updates or user interactions trigger data retrieval.

  4. Client-side Data Fetching with Third-party Libraries: Just as on the server side, third-party libraries like 'swr' can be employed to manage client-side data fetching. These libraries handle caching, revalidation, and other complexities, simplifying the process.

Setting up Next13 project

You need to have your project environment ready, follow the steps below to setup your project

  1. Create a folder where you want your project to reside, I named mine datafetch , you can choose any name for yours.

  2. Open the folder with VsCode studio

  3. Open your terminal

  4. Scaffold a new Nextjs Project by running

     npx create-next-app@latest .
    

    Congratulations on successfully creating a new NextJS project. Let's now move on to the practical implementation of getting data in NextJS.

Retrieving Data from FakestoreApi on the Server using the Fetch Method

In this section, you will be extracting data from the FakestoreApi by employing the 'fetch' API. This fetching mechanism is revered for its capabilities in retrieving information. By the end of this section, you'll have the proficiency to effectively retrieve data from the fakestore API and seamlessly present a beautiful shopping list.

To get started create a new folder in the app directory named 'serverFetch'. This new folder will house our code. Inside the 'serverFetch' directory, create a new file named 'page.jsx' where our code will be showcased.

Firstly, we'll write a function to fetch the data. This function retrieves product information from the fakestoreapi , and then converts it into JSON format.

async function getData() {
  const response = await fetch(`https://fakestoreapi.com/products`);
  if (!response.ok) {
    throw new Error('Failed to fetch Data');
  }
  return response.json();
}

Following the data retrieval, our next step is to exhibit the findings within the user interface. This task is encapsulated in a 'serverFetch' function:

Our next step after retrieving the data is to display the results in the user interface. The 'serverFetch' function contains code for it.

import React from "react";
import Image from "next/image";

async function getData() {
  const res = await fetch(`https://fakestoreapi.com/products`);

  if (!res.ok) {
    throw new Error("Failed to fetch Data");
  }

  return res.json();
}

const serverFetch = async () => {
  const data = await getData();
  console.log(data);

  return (
    <div className="w-full bg-gradient-to-r from-blue-500 to-blue-700 text-white py-10">
      <div className="container mx-auto">
        <h1 className="text-3xl font-semibold mb-6">New Stock Alert</h1>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {data?.map((item) => (
            <div key={item.id} className="bg-white p-4 shadow-md rounded-md transform hover:scale-105 transition-transform duration-300">
              <div className="h-44 relative overflow-hidden rounded-md">
                <Image
                  src={item.image}
                  layout="fill"
                  objectFit="cover"
                  alt={item.title}
                  className="rounded-md"
                />
              </div>
              <div className="mt-3">
                <h3 className="text-lg font-semibold">{item.title}</h3>
                <p className="text-gray-600 mb-2">{item.category}</p>
                <div className="flex items-center mb-2">
                  <span className="text-yellow-500 text-sm">
                    Rating: {item.rating.rate}
                  </span>
                  <span className="text-gray-500 text-sm ml-2">
                    Count: {item.rating.count}
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default serverFetch;

This code defines an asynchronous function named serverFetch that fetches data using the previously mentioned getData function, logs the fetched data, and then constructs a dynamic display of new stock items with their images, titles, categories, ratings, and counts in a visually appealing format.

Execute the code by running the command npm run dev in your terminal. Then, in your web browser, navigate to localhost:3000/serverfetch.

Conclusion

We've acquired a solid understanding of the principles and methods behind data fetching in Next.js, demonstrated through the hands-on exercise of retrieving product details from the fakestoreapi. However, the fetch API is only one option in the larger picture of data retrieval. In forthcoming segments of our data fetching series, We will explore various methods for obtaining data within the Next.js ecosystem in upcoming articles of our data fetching series.

Follow this space for a look at a variety of strategies that will add to your toolkit and show you all the alternatives available.

I'd love to connect with you via Twitter | LinkedIn | GitHub |