Is managing the UI state is hard, or we make it hard for ourselves by not paying attention?
How do we do that? ๐ค
We have this React component fetches the list of something and renders accordingly.
Pretty straightforward, huh?
Probably not ๐ฌ
Our state initializes with loading=false and fetchData is called on componentDidMount which means, right after the initial render.
This will cause a flash in the Loading text since it's displayed after we render the empty list in our initial state (data=[])
But programmers are pragmatic and smart people; we can fix this by initializing the state with loading=true?
โ - No more flashing UI.
๐ฐ - We say that something is loading but that is not the reality, nothing is literallyloading until fetchData is called.
Our state is lying, but we can live with that.
Request failed? Oh, snap!
Let's take one more step forward for a better UX and add a retry button to the error component.
OK, this would work for our beloved users.
But readability is not optimal because we're doing some nasty things. We need to perform a clean-up since error might be a leftover from the first call.
Again, we may come up with an ingenious solution to make that bearable by introducing a custom onRetry method.
โ - More readable and traceable.
๐ฐ - We are skipping a fundamentally crucial point, and our state is still lying.
Time to question our choices
Why can our state have an error while loading is true?
Why does our state have data=[] while loading is true?
Why is that possible to have data and error at the same time?