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

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? ...

React Tricks

REACT-TIPS React Tips Replace Redux with React Query As our application gets larger it becomes harder to manage state across our components, we may reach for a state management library like Redux. If our application relies on data that we get from an API, we often use Redux to fetch that server state and then update our application state. This can be a challenging process; not only do you have to fetch data, but you also need to handle the different states, depending on whether you have the data or are in a loading or error state. Instead of using Redux to manage data you get from a server, use a library like React Query. React Query not only gives you greater control over making HTTP requests in your React apps through helpful hooks and the ability to easily refetch data, but it also enables us to seamlessly manage state across our app components, of...

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...