Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Set State of React Component by Looping Over a JSON Array

This guide covers how to use the Axios HTTP client to request JSON data from an API, receive a JSON response, loop over the data it contains, and set the state of a React component based on this data.

Nov 1, 2020 • 5 Minute Read

Introduction

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.

      class SolarSystem Extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            planets: [],
            gasGiantsCount: 0
        }
    }

    componentDidMount() {
        ...
    }

    render() {
        ...
    }
}
    

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.

      import axios from 'axios';

class SolarSystem Extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            planets: [],
            gasGiantsCount: 0
        }
    }

    async componentDidMount() {
        const { data: planets }  = await axios.get(this.props.planetApiUrl),
                  gasGiantsCount = planets.filter(planet => planet.isGasGiant).length;

        this.setState({ planets, gasGiantsCount });
    }

    render() {
        ...
    }
}
    

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.

      ...

    render() {
        const { planets, gasGiantsCount } = this.state;

        const planetComponents = planets.map(planet => <Planet name={planet.name} type={planet.type} />);

        return (
            <div>
                <h2>{gasGiantsCount}</h2>
                <ul>{planetComponents}</ul>
            </div>
        )
    }
}
    

Conclusion

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.