One of the key tasks of a frontend developer is integrating backend APIs into apps. Modern APIs widely follow the RESTful architecture where an endpoint receives a request from the client and sends back a response irrespective of the client. GET
APIs or endpoints that are used only to retrieve data from a server using a popular data format called JSON (JavaScript Object Notation). They often send back a complex JSON object with deeply nested objects and arrays.
This guide aims to explain how you can retrieve relevant information from a complex JSON object in your React app and store that data in the state, or pass it down as props when required.
The example in this guide will build a small React app that consumes the endpoint https://reqres.in/api/unknown
by breaking down a complex JSON object into simple objects and arrays. The entire data set is fetched and stored by a parent component and then broken down into two separate objects. One object is passed as props to a child component that shows the information contained in that object to the user.
Create a blank react project by running :
1npx create-react-app react-complex-json-app
Install Axios, a third party library that goes well with React for making HTTP calls.
1npm install axios
Create two simple components to get started. First, the Colors
component
:
1import React from 'react';
2
3const Colors=()=>{
4 return(
5 <>
6 <h1>This is Colors component</h1>
7 </>
8 )
9}
10export default Colors;
Now create the Home
component and render the Colors
component inside it as demonstrated below
.
1import React from 'react';
2import Colors from './Colors';
3
4const Home=()=>{
5 return(
6 <>
7 <h1>This is home component</h1>
8 <Colors/>
9 </>
10 )
11}
12
13export default Home;
Finally, render the Home
component inside App.js
.
1import React from 'react';
2import './App.css';
3import Home from './Components/Home';
4
5function App() {
6 return (
7 <div className="App">
8 <h2>React JSON</h2>
9 <Home/>
10 </div>
11 );
12}
13
14export default App;
Consider the following code for making a GET
request to a REST API.
1import React,{useEffect,useState} from 'react';
2import Colors from './Colors';
3import axios from 'axios';
4
5const Home=()=>{
6 useEffect(()=>{
7 axios.get('https://reqres.in/api/unknown')
8 .then(res=>{
9 console.log(res)
10 })
11 .catch(err=>{
12 console.log(err);
13 })
14 },[])
15 return(
16 <>
17 <h1>{Data.Company}</h1>
18 <p>{Data.Description}</p>
19 <Colors/>
20 </>
21 )
22}
23
24export default Home;
The JSON response as it is contains a lot of unnecessary information (such as config
, headers
, etc.), and returns all relevant information inside a data
object. This data
object contains the actual data that the user might be interested in. A good and simple practice to analyze and break down complex JSON responses is using console
statements to see the properties attached to an object as demonstrated below.
1useEffect(()=>{
2 axios.get('https://reqres.in/api/unknown')
3 .then(res=>{
4 console.log('Response from main API: ',res)
5 console.log('Home Data: ',res.data.ad)
6 console.log('Colors Data: ',res.data.data)
7 })
8 .catch(err=>{
9 console.log(err);
10 })
11 },[])
The data
object contains two relevant objects attached as properties: data
and ad
. The ad
object is supposed to be consumed by the Home
component for displaying the name of the company and its motto.
1company: "StatusCode Weekly"
2text: "A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things."
3url: "http://statuscode.org/"
The data
object is an array of objects where each object contains details about a particular color.
10: {id: 1, name: "cerulean", year: 2000, color: "#98B2D1", pantone_value: "15-4020"}
21: {id: 2, name: "fuchsia rose", year: 2001, color: "#C74375", pantone_value: "17-2031"}
32: {id: 3, name: "true red", year: 2002, color: "#BF1932", pantone_value: "19-1664"}
43: {id: 4, name: "aqua sky", year: 2003, color: "#7BC4C4", pantone_value: "14-4811"}
54: {id: 5, name: "tigerlily", year: 2004, color: "#E2583E", pantone_value: "17-1456"}
65: {id: 6, name: "blue turquoise", year: 2005, color: "#53B0AE", pantone_value: "15-5217"}
First, create some state variables to store the entire data. The state variable Data
stores details that have to be shown on the Home
component, and colorsData
stores the details that have to be shown on the Colors
component
1const [Data,setData]=useState({
2 Company:'',
3 Description:''
4})
5const [colorsData,setColorsData]=useState([])
Populate these variables with data inside the .then()
method of the API call.
1useEffect(()=>{
2 axios.get('https://reqres.in/api/unknown')
3 .then(res=>{
4
5 let companyData=res.data.ad;
6
7 setData({Company:companyData.company,Description:companyData.text})
8 setColorsData(res.data.data)
9 })
10 .catch(err=>{
11 console.log(err);
12 })
13},[])
Output data from companyData
inside the Home
component:
1return(
2 <>
3 <h1>{Data.Company}</h1>
4 <p>{Data.Description}</p>
5 <Colors data={colorsData}/>
6 </>
Let's now wrap up the guide, with complete code as discussed above.
The final code for the Home
component is demonstrated below.
1import React,{useEffect,useState} from 'react';
2import Colors from './Colors';
3import axios from 'axios';
4
5const Home=()=>{
6 const [Data,setData]=useState({
7 Company:'',
8 Description:''
9 })
10 const [colorsData,setColorsData]=useState([])
11 useEffect(()=>{
12 axios.get('https://reqres.in/api/unknown')
13 .then(res=>{
14 console.log('Response from main API: ',res)
15 console.log('Home Data: ',res.data.ad)
16 let companyData=res.data.ad;
17 setData({Company:companyData.company,Description:companyData.text})
18 console.log('Colors Data: ',res.data.data)
19 setColorsData(res.data.data)
20 })
21 .catch(err=>{
22 console.log(err);
23 })
24 },[])
25 return(
26 <>
27 <h1>{Data.Company}</h1>
28 <p>{Data.Description}</p>
29 <Colors data={colorsData}/>
30 </>
31 )
32}
33
34export default Home;
Finally, using a component loop, output the information about colors inside the Colors
component.
1import React from 'react';
2
3const Colors=({data})=>{
4 return(
5 <>
6 {
7 data && data.map((d)=>{
8 return(
9 <div className="card" key={d.id} style={{background:d.color}}>
10 <div className="container">
11 <h4><b>{d.name}</b></h4>
12 <p>{d.color}</p>
13 </div>
14 </div>
15 )
16 })
17 }
18 </>
19 )
20}
21
22export default Colors;
Dealing with complex JSON responses is a necessity today to React developers. It can be tedious at times but isn't a difficult task altogether if done wisely by breaking down large pieces of data into smaller chunks. This can be done by properly observing how an endpoint is giving back data to the frontend, especially the name of the keys, the type of values returned, etc. Working with complex JSON responses also improves your debugging skills.