TanStackT
TanStack11mo ago
11 replies
efficient-indigo

Merge useQuery results

The api I work with often has the ability to fetch "moreData". For example:

const useTodos = ({ id, moreData }) =>
    useQuery({ queryKey: ['todos', id], queryFn: fetchTodos({ id, moreData }) });


If moreData is
undefined
then just the base result is returned. For example maybe something like post, author , etc. If you supply moreData: ['image', 'comments'] then the result will return an object with those keys as well.

What I'd like to do is keep these queries within the same cache regardless of whether or not moreData is supplied. The example above would do that - but the problem with keeping moreData out of the queryKey is that there will be times in the app where, for example, comments will be undefined when it shouldn't be. Imagine initially being on the Comments page, then going to just the Post page, then back to the Comments page. By the time you get back to the Comments page - comments will initially be undefined until the fetch successfully returns and updates the cache again.

Anyone else encounter a similar problem to this? Now that I'm thinking about it I wonder if keepPreviousData might be useful here...
Was this page helpful?