Use Type Narrowing without early function returns with React Query

Tomasz Ducin
InstructorTomasz Ducin
Share this video with your friends

Social Share Links

Send Tweet

When handling your loading and error states, you don't always want to render a result in place of the entire component.

In our server-side search component, since we are making a new query when we update our input, the entire component re-renders, including the search input itself.

To fix this we'd move those conditional renders into a ternary inside the component render.

[00:00] The issue that we have seen in the previous lesson is that whenever we change the input value, the template becomes blank for a moment and only this message is being displayed because the query is being in the pending state. And once the data arrives, then we can finally see the whole template back [00:19] again. So in some cases, the early returns within the if statements do their job, but sometimes we want some more piece of the template to be visible all the time and only conditionally render a smaller piece of the UI. So there are multiple different ways to do that. However, [00:39] we're just going to simply use 2 ternary operations. So what is important is that we are still going to create a cascade of if statements or alternatively, a switch case statement. And the thing is that we always need to walk into the else statement. So [01:00] these conditional renderings cannot be basically aside. They need to be chained if an if else, if else, if else kind of sequence. So let's start with the is pending. So if the query is in the pending state, let's just display what we have over here. And when [01:20] it's not, so the else branch, if we have an error, then we basically display the template, the message over here. So we have the error message. And, also, if it's still not the case, then we can carry on with the [01:40] employee listing. Now we also need to get rid of these remainings. And now we can see that basically, if it's pending, then there comes the message. If it's error, there another message. And otherwise, we need to have the data so we have the same sequence. But the difference is that we're going to see [02:00] the input and the drop down and potentially this fetching message. So let's see how this looks like. So let's refresh the page. And the data is here, but we can also, at the same time, we can see the input and it basically doesn't show and hide. So adapt your views to your [02:20] needs.