Skip to content

Contact sales

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

Add Values from a Promise to a List of Dynamic Data in React

This guide will demonstrate how to fetch data from a remote API and then update a component's state using the setState function.

Nov 5, 2020 • 4 Minute Read

Introduction

In order to build real-time, dynamic apps using React, you will inevitably need to update a list/array of data within a component based on data coming into your system via an external API.

This guide will demonstrate how to fetch data from a remote API and then update a component's state using the setState function.

Let's dive in!

Updating State Dynamically Using Promises

Promises are used to model asynchronous actions in your JavaScript code. In this example, you will see how promises are used with the built-in JavaScript Fetch API in order to create our HTTP requests.

The setState function that React provides on components allows you to asynchronously set the state of your component. React will then trigger a new render of your component's view, if applicable.

Below, you will see some example code that implements polling in a React component. The code requests a new data point from an external API every five seconds and then stops polling when the component is unmounted.

      class DynamicArrayComponent Extends React.Component {
    constructor(props) {
        super(props);
        this.interval;

        this.state = {
            dataPoints: this.props.dataPoints || [] // Set the initial state
        }
    }


    componentWillMount() {
        // Make the first request and then start polling.
        this.requestLatest();
        this.startPolling();
    }

    componentWillUnmount() {
        this.stopPolling();
    }

    requestLatest = () => {
        fetch(this.props.API_URL)
            .then(response => response.json())
            .then(dataPoint =>
                this.setState({
                    dataPoints: this.state.dataPoints.concat(dataPoint)
                })
            );
    }

    startPolling = () => this.interval = setInterval(this.requestLatest, 5000)

    stopPolling = () => {
        if (this.interval) {
            clearInterval(this.interval);
        }
    }

    // ....
}
    

The first part of the code above, within the constructor, sets up the initial dataPoints state and creates an internal component property for keeping track of the interval that is to be created.

The componentWillMount component lifecycle method uses the requestLatest and startPolling methods to make an initial request for data and then start polling. This is necessary because when you use setInterval in JavaScript, it will not immediately call the function that you pass it.

Let's take a closer look at the requestLatest method:

      requestLatest = () => {
    fetch(this.props.API_URL)
        .then(response => response.json())
        .then(dataPoint =>
            this.setState({
                dataPoints: this.state.dataPoints.concat(dataPoint)
            })
        );
}
    

Assuming that the external API is set up to dish out a new data point every five seconds, the code above fetches that new data and then uses the setState and Array.concat methods to add the data point to the component state. Note that when writing React code and using state, it is important that you use immutable data structures. The Array.concat method is a good choice here because it will return a new array. This ensures that, at a shallow level, you are dealing with an immutable component state.

From here, the componentWillUnmount component lifecycle method is used to call the stopPolling method, which uses the global clearInterval function to stop polling by clearing the created interval.

There you have it—just like that, you have added values from a promise to a list of dynamic data in React!

Conclusion

The setState function in conjunction with promises is all you need to dynamically add values to an array. The asynchronous nature of setState and the way that React uses a virtual DOM will ensure that your component is updated only when it needs to be updated.

For more information about setState and the possibilities there, please check out the React documentation.