Fetching JSON Data in Next.js A Beginner’s Guide

nextjsNextJs/Json

If you are learning next.js then you might wonder how to fetch a json/api and display it inside your project or you just want to know how to achieve that. In this guide I will help you with fetching json and then display it in your project too.

This guide is going to beginner's friendly so if you have just started with next.js then don't worry.

Step 1: Set Up Your Project Structure

First thing, lets setup basic project structure. Follow these steps :
  1. Create a "lib" folder : In this folder we will store out fetching logic file. You can create folder in root directory of project ( just like "app" folder ).
  2. Create a "getData.jsx" file : Inside your "lib" folder we will create "getData.jsx" file. In this file we will write our fetching logic.

Step 2: Write the Fetching Function

Now, lets define our asynchronous function that fetches data from API. export async function getData() { const res = await fetch("your link here"); return res.json() }

Step 3: Fetch Data in Your Server-Side Component

Now will fetch our data to a server-side component. Go to file in which you want to display your fetched data and follow :
  1. Import the getData function: In the component where you want to display the fetched data, import getData.
  2. Assign a const to fetched data : We will create a new const allData and assign our fetched data to it.

Step 4: Display the Fetched Data

You can easily display the fetched data by mapping through it in your component. In the example above, each item is rendered in a list, with a unique key prop to help React manage the elements efficiently.

Conclusion

Congratulations! You've successfully set up a Next.js application to fetch and display JSON data from an API. By following these steps, you can enhance your applications with dynamic content, making them more interactive and engaging. Happy coding!

© All right reserved by throughDev