Handling loading and error states in T3

Hi I have just started using the T3 stack and was wondering what's the best practice for handling error loading states on the client, because I try in my frontend to do something like this.
const { data: jobs, isLoading } = api.job.getJobs.useQuery({
searchQuery,
take,
skip,
});

if (isLoading) return <Spinner size="lg" />;
const { data: jobs, isLoading } = api.job.getJobs.useQuery({
searchQuery,
take,
skip,
});

if (isLoading) return <Spinner size="lg" />;
When I do this it seems like my search input keeps re-rendering and losing focus after each keystroke. Is there something I'm missing and is this how I should be handling the state?
8 Replies
Holy Spirit Activist | John ☦
When I get rid off the spinner, it works fine without re-rendering after each stroke
stoyko
stoyko9mo ago
It does rerender, you just don't see it. What you might want to do is setup a debounce which will help you not send a request on each keystroke, but after a specific delay. https://www.developerway.com/posts/debouncing-in-react This is the first article I found in google about it, but I am sure you can find more information to help you
How to debounce and throttle in React without losing your mind
Deep dive into debounce and throttle in React. What is debounce and throttle, how to use them in React properly, how to avoid breaking them when state and re-renders are involved.
Holy Spirit Activist | John ☦
But the thing is that I'm sending requests on each keystroke anyway, so why does the text input lose focus when I have that fi statement in my Home page, but without it, the text retains its focus.
stoyko
stoyko9mo ago
because you have an early return. You can try it without the spinner as well. Just setup a console.log('rerender'); and see how it updates on each keystroke
Holy Spirit Activist | John ☦
But I don't understand why does it lose focus when I have the spinner? How would you handle the loading state in this case then?
stoyko
stoyko9mo ago
Because you render a different component whenever you have isLoading set to true, which in your case, is in every single key stroke press. I would handle it by adding a debounce. This will allow you to type a much longer input before your spinner shows. Or change it so that the spinner is shown only in the content that sits wherever your data is shown. This way, you won't lose focus in your input field, while also showing a spinner on the page while searching
Holy Spirit Activist | John ☦
Okay thanks a lot for the help I appreciate it.
stoyko
stoyko9mo ago
No problem. If you think your question is answered, mark it as solved.
Want results from more Discord servers?
Add your server