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?