0

I have a Node Js API where I get my database data with a find function. It works perfectly and send my results. Using React and Axios, I get the data but as soon as I pass the data into setState it sends null.

Here is my API find() function

dbo.collection("students").find({}).toArray(function(err, result) {
        if (err) throw err;
        var students = result;
        reponse.send(students);
        db.close();
    });

And here is my Axios constructor() and componentDidMont()

    constructor() {
    super();
    this.state = {
      students: [],
    }
  }

    componentDidMount() {
    axios.get("http://localhost:3333/").then((data) => {
      console.log(data);
      this.setState({students:data.data.students});
      console.log(this.state);
    });
  }

console.log(data) return this

`Object { data: (33) […], status: 200, statusText: "OK", headers: {…}, config: {…}, request: XMLHttpRequest }`

While console.log(this.state) return this

Object { students: undefined }

Sponge
  • 23
  • 5

1 Answers1

0

Firstly state updates are async so you wouldn't see the updated state immediately

Secondly, the response data has data which is an array, so you just need to set the state with data.data

this.setState({students:data.data});
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400