So I'm just barely learning reactJS and got a little confused for reading an if else in the conditional rendering that I've been written. This is the code that I've wrote:
this.setState({
loading: true
})
axios('https://api.randomuser.me/?nat=USA&results=5').then(response => this.setState({
users : response.data.results,
loading : false
}))
}
componentWillMount() {
this.getUser()
}
render() {
return (
<div className="App">
{!this.state.loading ?
this.state.users.map(user =>
<div>
<h2>{`${user.name.first} ${user.name.last}`}</h2>
</div>) : 'Loading'}
{console.log(this.state.loading)}
</div>
);
}
When the program is still reaching for the API data, a 'Loading' string will be displayed and when the program already get the API data, it will disappear and displayed the data instead
I'm doing trial and error for the part in render(). first I put this.state.loading without ! (false) and the app just displaying Loading all the way with no end. But when I put ! (false), the program works just fine.
So I got confused on how to read the if else statement in this occurence, like
If
this.state.loadingcondition is false (with!), write the<h2>. Else display 'Loading' string
But the problem is, the condition of this.state.loading before the API data obtained is true, since I wrote it before in here:
this.setState({
loading: true
})
axios('https://api.randomuser.me/?nat=USA&results=5').then(response => this.setState({
users : response.data.results,
loading : false
}))
}
Then why the Loading is working? Please tell me how to actually read this logic, thank you before.
this.state.loading == true ? console.log("still loading") : console.log("loaded");
you could check the value like this
try to change
!this.state.loading
to
this.state.loading == true
so if the loading state is equal to true it will display "still loading", and if the loading state is set to false it means that the ajax request is done and it will display "loaded".