Skip to main content

Fetch-json-data-in-react-app

Fetch Data from a JSON File in a React App | Pluralsight
React

Introduction

Creating API mockups for local testing and development allows you to work in a faster development environment. One way to implement an API mockup is to copy the JSON data to a local file in your project directory and make your fetch or GET calls to that file instead of the real database. As fetching data from an external source is still an asynchronous task, there are a number of errors you can run into while loading data from a JSON file. This guide will demonstrate how to correctly fetch data from a JSON file in your React app and consume it on the frontend.

Setting Up a Local JSON file

In a blank Create React App project, create a local JSON file named data.json inside the public directory. Your Fetch API calls made from a React component always looks for files or any other relevant assets inside this public directory. Create-React-App doesn't put your assets automatically inside this directory during compilation so you have to do this manually.

Next, put some dummy JSON data inside this file. For demonstration purposes, the JSON data used in the example below is generated from JSON Generator. If you are using your own JSON, ensure that it is correctly formatted.

Consuming Local JSON Data Using Fetch API

The next step you need to perform is fetching this data correctly. Create a method getData() that fetches local JSON using JavaScript's fetch API and call it inside useEffect as shown below.

1  const getData=()=>{
2    fetch('data.json'
3    ,{
4      headers : { 
5        'Content-Type': 'application/json',
6        'Accept': 'application/json'
7       }
8    }
9    )
10      .then(function(response){
11        console.log(response)
12        return response.json();
13      })
14      .then(function(myJson) {
15        console.log(myJson);
16      });
17  }
18  useEffect(()=>{
19    getData()
20  },[])
javascript

The path to your JSON file should be either 'data.json' or './data.json'. Other relative paths might land you a 404 error while trying to access that resource. You also need to pass in some headers indicating the Content-Type and Accept as application/json to tell your client that you are trying to access and accept some JSON resource from a server.

Loading Data into the Component

Create a state using the useState hook to store this data and render it on the DOM.

1const [data,setData]=useState([]);
javascript

Assign the JSON data inside your fetch call to this state variable.

1const getData=()=>{
2    fetch('data.json'
3    ,{
4      headers : { 
5        'Content-Type': 'application/json',
6        'Accept': 'application/json'
7       }
8    }
9    )
10      .then(function(response){
11        console.log(response)
12        return response.json();
13      })
14      .then(function(myJson) {
15        console.log(myJson);
16        setData(myJson)
17      });
18  }
javascript

Depending on your JSON's structure, put relevant checks inside the return statement of your component before rendering or loading this data. The GET call for your JSON resource is made when the component mounts on the DOM. However, since it is an asynchronous task your return statement is executed before the API call is made. Because you are updating the state after fetching the required data, a re-rendering of the component updates the DOM with JSON data stored inside the state. The JSON used here is an array of objects, so the relevant check would be to check if the state exists and consequently verify if it has a non-zero length as shown below.

1 return (
2    <div className="App">
3     {
4       data && data.length>0 && data.map((item)=><p>{item.about}</p>)
5     }
6    </div>
7 );
jsx

If your JSON returns an object, simply check your state to be not null at the time of outputting it, otherwise you might get an error.

Have a look at the entire code below.

1import React,{useState,useEffect} from 'react';
2import './App.css';
3
4function App() {
5  const [data,setData]=useState([]);
6  const getData=()=>{
7    fetch('data.json'
8    ,{
9      headers : { 
10        'Content-Type': 'application/json',
11        'Accept': 'application/json'
12       }
13    }
14    )
15      .then(function(response){
16        console.log(response)
17        return response.json();
18      })
19      .then(function(myJson) {
20        console.log(myJson);
21        setData(myJson)
22      });
23  }
24  useEffect(()=>{
25    getData()
26  },[])
27  return (
28    <div className="App">
29     {
30       data && data.length>0 && data.map((item)=><p>{item.about}</p>)
31     }
32    </div>
33  );
34}
35
36export default App;
javascript

Conclusion

You can also use a powerful third-party library called Axios to make GET calls to a local JSON file instead of fetch API. By loading data directly from a local JSON file you can save your server from tons of unnecessary calls in local development. Alternately, by saving the JSON file as a regular JavaScript file and exporting the entire object globally, you can use it inside any component and save a considerable amount of development time when working with external APIs.

Comments

Post a Comment

Share your thoughts!

Popular posts from this blog

Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms.

Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms. Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms. “JavaScript’s global scope is like a public toilet. You can’t avoid going in there, but try to limit your contact with surfaces when you… Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms. Photo by Florian Olivo on  Unsplash “ J avaScript’s global scope is like a public toilet. You can’t avoid going in there, but try to limit your contact with surfaces when you do.” ― Dmitry Baranowski Here’s another (much) more simple article I wrote on the subject: Closures In Javascript Answer A closure is a function defined...

links

links Absolutely Everything You Could Need To Know About How JavaScript TOC & Condensed Links **** **** **** **** **** 1 2 3 4 5 leonardomso/33-js-concepts *This repository was created with the intention of helping developers master their concepts in JavaScript. It is not a…*github.com Call stack - MDN Web Docs Glossary: Definitions of Web-related terms MDN *A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its…*developer.mozilla.org Understanding Javascript Function Executions — Call Stack, Event Loop , Tasks & more *Web developers or Front end engineers, as that’s what we like to be called, nowadays do everything right from acting as…*medium.com Understanding the JavaScript call stack *The JavaScript engine (which is found in a hosting environment like the browser), is a single-threaded interpreter…*medium.freecodecamp.org Javascript: What Is The Execution Context? ...

Bash Proficiency

Bash Proficiency In Under 15 Minutes Bash Proficiency In Under 15 Minutes Cheat sheet and in-depth explanations located below main article contents… The UNIX shell program interprets user commands, which are… Bash Proficiency In Under 15 Minutes Cheat sheet and in-depth explanations located below main article contents… The UNIX shell program interprets user commands, which are either directly entered by the user, or which can be read from a file called the shell script or shell program. Shell scripts are interpreted, not compiled. The shell reads commands from the script line per line and searches for those commands on the system while a compiler converts a program into machine readable form, an executable file. LIFE SAVING PROTIP: A nice thing to do is to add on the first line #!/bin/bash -x I will go deeper into the explanations behind some of these examples at the bottom of this article. Here’s some previous articles I’ve written for more advanced users. Bash Commands That Sa...