Status instead of isLoading boolean?
Joanna Otmianowska
Posted on April 26, 2021
When I saw the article 'Stop using isLoading boolean' written by Kent C. Dodds my first thought was - what's wrong with isLoading
boolean? Why shouldn't I use it? Then I read it. And saw his point.
It is a common practice to use isLoading
boolean to show some placeholder or spinner when data in our app is loading. This is fine - you set isLoading
to false
, change it to true
when data is loading and when data is here - put it back to false
. But what happens when error occurs? Data is not loading but there is no data to show either. We start to add more conditions - first not loading and no error, then for not loading but with error, another one for loading. Do you see the point?
What Kent suggests in his approach is having status with different enum values for every case e.g. 'idle'
, 'resolved'
, 'rejected'
. In the code then we can go like (examples based on the article that I mentioned earlier):
if (status === 'idle') {
return <div>Data is loading...</div>
}
if (status === 'resolved') {
return <div>{Fetched data}</div>
}
if (status === 'rejected') {
return <div>Something went wrong!</div>
}
Thanks to that we can set status for particular case after every activity and there is no need for double conditions (like is not loading and there is no errors etc).
To get rid of equal signs we can put status info in variables.
const isLoading = status === 'idle';
if (isLoading) {
return <div>Data is loading...</div>
}
And that's it! I recommend reading Kent's article for deeper explanation and more examples.
Posted on April 26, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 18, 2024