0
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?

Audrey Wong
  • 71
  • 1
  • 1
  • 8

2 Answers2

0

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;

Black Plum
  • 389
  • 2
  • 10
  • Hi, I still didn't manage to get the data out. I tried this.setSatet({message: "hello"}) inside of getData and didnt manage to get the message out either. – Audrey Wong Jul 26 '21 at 07:56
  • I modified my answer and made a simple version, this should be what you want, because mine can run – Black Plum Jul 31 '21 at 06:04
  • hi, sorry for the late reply but turns out it was my API that was not deployed... :(. code works fine with the componentdidmount(). thanks! – Audrey Wong Oct 03 '21 at 04:38
0

If you are using 'async' and 'await' you don;t have to use then() function you can write

const data = await axios.get("url")
console.log(data.data)
this.setState({message:data.data})
Vismay
  • 23
  • 5