T
TanStack17mo ago
genetic-orange

query when filters change, but keep the current results until new data is loaded

const { isLoading, error, data: cars} = useQuery({ queryKey: ['jobs', JSON.stringify(filters)], queryFn: () => fetchCars(), }) I'm just iterating over cars and rendering them. I have a text input field and when i press a key, i update the redux store (filters) The problem is, everytime I press a key, now I'm seeing 1 second of loading screen (or just an empty div, based on my configuration). Im guessing that is because "cars" variable is set to undefined when im making a new fetch this code, and while its undefined, thats why its not showing any cars on the DOM (im not 100% sure) What I want is, when im making a new request, it should still show the results from previous query. i dont want to see an empty screen until the new data is loaded. Tried "keepPreviousData" but it throw some weird error and I couldn't fix it.
4 Replies
eastern-cyan
eastern-cyan17mo ago
what was the error? have you tried placeholderData: previousData => previousData ?
genetic-orange
genetic-orangeOP17mo ago
thanks, that worked! I made some research and asked GPT aswell but couldn't find this solution before, thanks again. Do you think thats a valid approach? is this common? I make a new query with every text input and I feel like showing previous data until new ones are loaded is a better approach, rather than showing "loading..." with every input. what do you guys think?
extended-salmon
extended-salmon17mo ago
Yes this is common. The observer keepPreviousData
eastern-cyan
eastern-cyan17mo ago
yeah it's common, it's usually a UX decision, and how long does it take to complete the request, if that's a slow endpoint you don't want your users seeing stale data for too long, I like using skeletons as spinners and not doing the lagged queries approach, because I don't want an impatient user reporting that my search doesn't work

Did you find this page helpful?