Author avatar

Zachary Bennett

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

Zachary Bennett

  • Nov 5, 2020
  • 4 Min read
  • 82 Views
  • Nov 5, 2020
  • 4 Min read
  • 82 Views
Web Development
Front End Web Development
Client-side Frameworks
React

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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);
        }
    }

    // ....
}
jsx

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:

1
2
3
4
5
6
7
8
9
requestLatest = () => {
    fetch(this.props.API_URL)
        .then(response => response.json())
        .then(dataPoint =>
            this.setState({
                dataPoints: this.state.dataPoints.concat(dataPoint)
            })
        );
}
jsx

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.

1