How To Fetch Data from a JSON File in React.js

Udemezue John - Oct 6 - - Dev Community

Introduction.

Fetching data from a JSON file in React is one of those foundational tasks that you'll inevitably come across when building any dynamic web application.

In this guide, I’ll walk you through the process of loading data from a JSON file and displaying it in a React component.

Along the way, I’ll cover a few common methods to handle data, from using static JSON files to fetching them dynamically via APIs.

With React’s flexibility, you’ll be able to adapt the approach based on the structure and scale of your project.

Why JSON?

JSON (JavaScript Object Notation) has become the go-to format for data exchange across the web, thanks to its lightweight structure and ease of use.

According to a report from Statista, JSON is one of the most widely used data formats, employed by 79% of developers in 2022.

So, whether you’re building a small project or scaling up to something larger, knowing how to handle JSON in React will be a key skill.

By the end of this article, you’ll not only be able to fetch data from a JSON file in React but also manage that data efficiently and render it dynamically within your app’s components. Let’s dive in!

How Do I Fetch Data from a JSON File in React.js?

Working with JSON data is a fundamental part of web development, and fetching that data in a React.js application is both common and essential.

Whether it's static data from a file or dynamic content from an API, knowing how to handle JSON files in React will be a crucial skill.

I’ll walk you through the process of fetching data from a JSON file, step by step, using React.

Setting Up the React Environment.

First, you’ll need to ensure that you have a React environment set up. If you don’t already have a React project created, you can quickly set one up using create-react-app.

Open your terminal and run the following command:



npx create-react-app json-fetch-example


Enter fullscreen mode Exit fullscreen mode

Navigate to the newly created project directory:



cd json-fetch-example



Enter fullscreen mode Exit fullscreen mode

Start the development server:



npm start


Enter fullscreen mode Exit fullscreen mode

This will launch your application in the browser at



http://localhost:3000.



Enter fullscreen mode Exit fullscreen mode

Adding the JSON File.

For this example, I’ll create a simple data.json file containing some dummy data.

You can place this file in the public folder of your project. This folder is accessible by the React application at runtime.

Here’s an example data.json file:



[
  {
    "id": 1,
    "name": "John Doe",
    "email": "johndoe@example.com"
  },
  {
    "id": 2,
    "name": "Jane Smith",
    "email": "janesmith@example.com"
  },
  {
    "id": 3,
    "name": "Sam Johnson",
    "email": "samjohnson@example.com"
  }
]


Enter fullscreen mode Exit fullscreen mode

I’ll place this file in the public folder like so: public/data.json.

Fetching JSON Data in React.

Now, I’ll focus on fetching this JSON data and displaying it in the app. For fetching the data, I can use the native fetch() API, which is modern and widely supported.

In the App.js file (or any other component file you prefer), I’ll write the logic to fetch the JSON data and handle it.



import React, { useEffect, useState } from "react";

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("/data.json")
      .then((response) => response.json())
      .then((data) => setData(data))
      .catch((error) => console.error("Error fetching data:", error));
  }, []);

  return (
    <div>
      <h1>User Data</h1>
      <ul>
        {data.map((user) => (
          <li key={user.id}>
            {user.name} - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

Here’s what’s happening in this code:

  • State Initialization: I’m using the useState hook to create a piece of state called data. Initially, this is an empty array, which will eventually store the fetched data.
  • Fetching Data: Inside the useEffect hook, I’m calling the fetch() function, which sends a GET request to the data.json file located in the public directory. After fetching the data, I’m parsing the response using response.json() to convert it to a JavaScript object or array. Once the data is parsed, I’m updating the data state using setData(data).
  • Rendering the Data: In the JSX, I’m rendering a list of users by mapping over the data array and displaying each user’s name and email.

Handling Errors.

It’s important to handle potential errors that could occur during data fetching.

For example, the file might not be found, or there could be a network issue. I’ve added a .catch() block to log any errors that occur during the fetch operation.

If you want to provide more user-friendly error messages, you can set an additional piece of state to track errors and display them in the UI. Here's an enhanced version of the component that handles errors:



import React, { useEffect, useState } from "react";

function App() {
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch("/data.json")
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => setData(data))
      .catch((error) => setError(error.message));
  }, []);

  return (
    <div>
      <h1>User Data</h1>
      {error ? (
        <p>Error fetching data: {error}</p>
      ) : (
        <ul>
          {data.map((user) => (
            <li key={user.id}>
              {user.name} - {user.email}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

In this example, I’m checking the response status before parsing the JSON.

If the response is not OK (e.g., a 404 or 500 error), I’m throwing an error, which is caught and displayed to the user.

Fetching JSON from External APIs.

If you’re working with a live API instead of a local JSON file, the process is nearly identical.

The only difference is that instead of using a relative path like "/data.json", you’ll use the full URL of the API.

Here’s an example where I’m fetching data from a public API:



import React, { useEffect, useState } from "react";

function App() {
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.json();
      })
      .then((data) => setData(data))
      .catch((error) => setError(error.message));
  }, []);

  return (
    <div>
      <h1>User Data</h1>
      {error ? (
        <p>Error fetching data: {error}</p>
      ) : (
        <ul>
          {data.map((user) => (
            <li key={user.id}>
              {user.name} - {user.email}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default App;



Enter fullscreen mode Exit fullscreen mode

In this case, I’m fetching user data from the jsonplaceholder API, which is a free, fake REST API for testing and prototyping.

Conclusion.

Fetching data from a JSON file in React is a straightforward process using the fetch() API. The key steps are:

  • Using useState to manage the fetched data.
  • Using useEffect to perform the data fetch when the component mounts.
  • Parsing and handling the JSON response.
  • Rendering the fetched data in your component.

With these basics covered, you can now fetch data from local JSON files or external APIs in your React applications.

JSON handling in React is an integral part of building dynamic web apps that communicate with a backend or display static datasets.

. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player