Search code examples
reactjsapigetrendersetstate

How do I change a state after getting data from API?


constructor(props) {
        super(props);
        this.state = {
            message: ""
        };
    }

    async getData() {
        this.setState({...this.state})
        await axios.get("https://g...")
        .then(function(response) {
            console.log(response);
            this.setState({message: response.data})
        }).bind(this)
    }

    render() {
        return (
            <div>
                {this.state.message}
            </div>
        );
    }

I tried to use this code to get data from the API. However, the message that is printed out is only linked to the original constructor, and the getData() function does not change the state. How should I go around changing the state after getting data?


Solution

  • You should use componentDidMount, and put the function requesting data in componentDidMount life circle.

    By the way, you can add a loading to enhance the user experience : )

    import React from 'react';
    
    import "./styles.css";
    
    const BASE_URL = 'https://api.github.com';
    
    class App extends React.Component {
    
      constructor(props) {
        super(props);
        this.state = {
          message: ''
        }
      }
    
      componentDidMount() {
        this.getData();
      }
    
      async getData() {
        try {
          const result = await fetch(`${BASE_URL}/repos/facebook/react`);
          const toJson = await result.json();
          const stringify = JSON.stringify(toJson, null, 2);
    
          this.setState({
            message: stringify
          })
        } catch (error) {
          // ignore error.
        }
      }
    
    
      render() {
        const { message } = this.state;
    
        return (
          <div>
            {message}
          </div>
        )
      }
    }
    
    export default App;