"Simplify Your Data Handling: Learn to Load JSON Files into React with UseEffect, UseState, and Fetch API"

"Simplify Your Data Handling: Learn to Load JSON Files into React with UseEffect, UseState, and Fetch API"

"The Beginner's Guide to Loading JSON Data into React Components with UseEffect, UseState, and Fetch API"

Fetching data objects or trying to access an array of data from a json file could be quite a hassle as compared to simply importing the file from the file path and then reading the data using a map method.

However, the former is considered more of a best practice than the later and in most cases offers flexibility of options with respect to how the user can manipulate that data.

In this article, I would be explaining in the simplest and most understandable way possible how to read data from a JSON file in React using the UseEffect hook, UseState hook and Fetch API.

The JSON File Format

JSON files (fileName.json) have a standard format which is quite dissimilar to the regular files (fileName.js). A JSON file containing data usually begins with a bracket [ ] indicating an array. Then the objects are put into that array in curly braces ending with commas until the last object. The key-value pairs in these objects are also wrapped in a double quotation mark. Below is an example of a JSON file format.

  [
    {
        "id": 1,
        "firstName": "Ani B",
        "lastName": "Somto",
        "age": 20,
        "website": "aniB.com" 

    }
]

Also note that your JSON file should be located in the PUBLIC folder and NOT in the SRC or ROOT directory of your React Application. The JSON file should contain no imports neither is it exporting any file.

Fetching The Data

Navigating to the App.js or wherever you want this Data to be displayed, you import the useEffect and UseState hook. Using the useState hook, you set the initial state of the data to an empty array: [ ].

 import React, { useState } from "react";
    const DisplayPage = () => {
    const [data, setData] = useState([]);
return (
    <>
         // the jsx element goes here //
    </>
)}; 
export default DisplayPage

Adding to the above code block, you import the useEffect hook which takes care of the data fetching from the JSON file and updating the state of the data from an empty array to an array containing the data.

 import React, { useState, useEffect } from "react";
    const DisplayPage = () => {
     const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch("/data.json");
        const jsonData = await response.json();
        console.log(jsonData); // logs the data to the console
        setData(jsonData);
      } catch (error) {
        console.log(error, "error"); // logs the error message to the console
      }
    };
    fetchData();
  }, []);    

return (
    <>
       // the jsx element goes here //
    </>
)}; 
export default DisplayPage

Explaining the above code block, the useEffect hook is firstly imported from react. The useEffect hook is clearly seen housing an asynchronous function which makes an HTTP Fetch request to the json file containing the data. After getting a response, which is the data you append it with a .json( ) which extracts the JSON data from the response. It basically parses the data in the response body and returns it as a javascript object. The JSON data is then stored in the jsonData variable and passed to the setData function to update the state of the data variable.

Rendering the data in the JSX

Now that we have successfully gotten the data, we can now get get the values of the objects in the array and use it in our application.

• the code below contains only the returned jsx of the application.

return (
    <>
    {
    data.map((dataItem) => (
    <div key = {dataItem.id}>
    <p> {dataItem.firstName} </p>
     <p> {dataItem.lastName} </p>
    <a href=`${dataItem.website}`> Client Website </a>
    </div>
    )
)}   
    </>
)};

If you still encounter problems reading the JSON file into your react component, ensure that the following are in place :

  • Inside Fetch Method, you should pass just the public file name only. This should look like "./data.json". Avoid using absolute paths like "./public/data.json"

  • ensure that the data.json is placed in the public directory

  • use the json() method to get data from the response

  • do not use import file in the fetch method url

  • check that the json file format is correct

You've gotten to the end of this article. Kindly drop a like, comment and share if you found value in this article. Questions and contributions are also welcome. Your engagements would be appreciated.

Keep Building !