Paulos3000
Paulos3000

Reputation: 3545

Axios AJAX call in React returning only initial state

I'm trying to make a simple AJAX call using Axios in React, but I can't figure out where I'm going wrong.

Here is what I have so far (within my component):

ComponentDidMount() {
   axios.get('https://jsonplaceholder.typicode.com/users')
      .then( res => {
         const users = res
         this.setState({ users });
      });
}

render() {
   console.log(this.state.users)   // returns the **initialised EMPTY array**
   return (
   <div>
      {this.state.users.map( user => <p>{user.name}</p>)} // returns nothing
   </div>
   )
}

I am accessing a simple array at the URL given in the .get() method (check it out to see it's structure if necessary). I then chain on the .then() promise and pass the res argument in an arrow function.

Then I assign the users variable to the result, and attempt to set the state as this. So at this point I'm expecting this.state.users to equal the resulting array.

However...

A) When I try console.log(this.state.users), it returns the initialised empty array

B) When I try to render a map of the array, iterating through the name property on each object, again, nothing.

Where am I going wrong?

Upvotes: 1

Views: 2215

Answers (2)

Phi Nguyen
Phi Nguyen

Reputation: 3056

typo. It should be componentDidMount instead of ComponentDidMount.

Upvotes: 2

fabio.sussetto
fabio.sussetto

Reputation: 7065

A part from the typo (as Phi Nguyen noted), a few other things to fix:

1) Axios resolves the promise with a response object. So to get the results you need to do:

   axios.get('https://jsonplaceholder.typicode.com/users')
     .then( res => {
      const users = res.data;  // Assuming the response body contains the array
      this.setState({ users });
    });

Check out the docs about the response object here: https://github.com/mzabriskie/axios#response-schema

2) If there's an exception (your request fails) you probably want to handle it instead of swallowing it. So:

 axios.get('https://jsonplaceholder.typicode.com/users')
   .then( res => {
     const users = res.data;  // Assuming the response body contains the array
     this.setState({ users });
   })
   .catch(err => {
      // Handle the error here. E.g. use this.setState() to display an error msg.
   })

Upvotes: 2

Related Questions