Waiting for fresh data before displaying component
Hi! I'm creating forms that use the technique described in https://tkdodo.eu/blog/react-query-and-forms, where react-query is used to populate the initial data but then it's turned into local state for the form while it's being edited.
If there is stale data already cached, then during the component load I might accidentally use the stale data as the initial data. What's the recommended way to wait for fresh data before rendering the form? Currently I just want for
query.data !== undefined but I was wondering if it might be enough to replace that with query.isFetching or something else. Thank you!4 Replies
vicious-gold•3y ago
Curious about this as well. I had the same issue a while ago, I basically wanted to ignore cached data for initializing the form, and needed to wait for fresh data.
At the time I solved it with some complicated logic based on
isSuccess and isRefetching which doesn't feel right. Now I'm wondering if setting cacheTime to 0 for that query would help 🤔flat-fuchsia•3y ago
check
isFetchedAfterMount and wait for it to become true
Or set a smaller cacheTime to gc the data earliervicious-gold•3y ago
Ah true, that works for refetches resulting from a component being mounted. I was also concerned about
refetchOnWindowFocus but that should be disabled for that query since we don't want to wipe the form data after its been initialized anyway.relaxed-coralOP•3y ago
@TkDodo 🔮 thanks!
isFetchedAfterMount doesn't seem to work in my case because I won't know if the query has been invalidated or not. I could do something like const isFresh = query.isStale ? query.isFetchedAfterMount : query.data !== undefined ("if the query is stale, are we done refetching? otherwise have we loaded the initial data?") but this doesn't feel right
What I'd really like to express is "do I have the latest known result of this query" before I display the form. The "latest" being the cached query data if it hasn't been invalidated, otherwise the latest fetched result that was fetched during mount (if it had been invalidated)
or maybe just const isFresh = query.isSuccess && !query.isStale?