Author avatar

Zachary Bennett

Set State of React Component by Looping Over a JSON Array

Zachary Bennett

  • Nov 1, 2020
  • 5 Min read
  • Nov 1, 2020
  • 5 Min read
Web Development
Client-side Frameworks
Front End Web Development


JSON, HTTP, and React go hand in hand. Odds are, you will need to interact with a JSON array of data at some point while building your React app.

In this guide, you will learn how to use the Axios HTTP client to request JSON data from an API. Then, you will learn how to receive a JSON response, loop over the data this response contains, and set the state of your React component based on this data

Let's get started!

Note: This guide assumes that you are working within a React app that has been created using create-react-app.

Requesting JSON Data

The first part of looping over a JSON array involves actually requesting the data! To request data from an API, we must start by using an HTTP client. In this guide, we have chosen Axios as our HTTP client library of choice. There are many alternatives! Fetch is a great, native client that you can use if you are trying to restrict the number of dependencies you are using in your app.

To download Axios, navigate to your root project directory where your package.json file is located, and run the command: npm install --save axios. Now you have Axios installed inside of your React project and can start using it!

In the code below, you will see the basic shell of a SolarSystem component. This component's job is to request a list of planets from the server via HTTP and then render a list of Planet components based on the response. The number of gas giants will also need to be counted by looping over the JSON array contained within the response.

1class SolarSystem Extends React.Component {
2    constructor(props) {
3        super(props);
5        this.state = {
6            planets: [],
7            gasGiantsCount: 0
8        }
9    }
11    componentDidMount() {
12        ...
13    }
15    render() {
16        ...
17    }

First, you will need to set the planets state of the component based on a list of planets requested within the componentDidMount lifecycle method. The componentDidMount lifecycle method will ensure that the planet's data is only requested after the initial render of the SolarSystem component. This is helpful because you can display a simple loading screen while you wait for the request to complete.

Below is the updated code that shows how to use Axios to make a request to the private planets API.

1import axios from 'axios';
3class SolarSystem Extends React.Component {
4    constructor(props) {
5        super(props);
7        this.state = {
8            planets: [],
9            gasGiantsCount: 0
10        }
11    }
13    async componentDidMount() {
14        const { data: planets }  = await axios.get(this.props.planetApiUrl),
15                  gasGiantsCount = planets.filter(planet => planet.isGasGiant).length;
17        this.setState({ planets, gasGiantsCount });
18    }
20    render() {
21        ...
22    }

Wow, that was easy! In the above code, you first imported the Axios HTTP client library. Then, you marked componentDidMount as an async function. This enables the use of theawait keyword in order to resolve the Promise returned from the call to axios.get.

Once the response successfully loaded, you then had access to an Axios response object. One of the nice things about Axios is that it automatically parses the JSON for you! You can access this JSON on the data field of the response object. In the above code, we make use of JavaScript's object destructuring capabilities to grab the data field off of the response object and rename it to planets. In this case, the data field comprises our already-parsed JSON array.

With access to the JSON array you need, you then looped over it using one of JavaScript's Array prototype functions. In this case, you can see that your code loops over the planets and counts the number of gas giants in the solar system.

Finally, you then used the setState function in order to set the planets and gasGiantsCount state of the component.

With your data requested, now it's time to load your view. Remember, this component simply wants to display a list of Planet components. This can be achieved by implementing the following render function.

1    ...
3    render() {
4        const { planets, gasGiantsCount } = this.state;
6        const planetComponents = => <Planet name={} type={planet.type} />);
8        return (
9            <div>
10                <h2>{gasGiantsCount}</h2>
11                <ul>{planetComponents}</ul>
12            </div>
13        )
14    }


Working with JSON arrays is a crucial skill when creating any web app. In React, you can make working with JSON arrays easy by using an HTTP client like Axios to help you with things like the automatic parsing of JSON. Tools like Axios will help make your job easier by letting you write less code!

Of course, requesting JSON isn't the only thing Axios can help you out with. Eventually, you will want to send JSON arrays within your React app as well! For more information regarding Axios please check out the Axios documentation.