I have data stored in a single folder. However, I wish to handle them separately within React Query. Furthermore, whenever there’s a change in the cached data, I want it to trigger a corresponding update in the component’s state, leading to a re-render of the application.
const { data: { bookmark: bookMark, reading: bookRead } = {}, error, isLoading } = useQuery({
queryKey: ['userData', userUID],
queryFn: getUserData,
staleTime: Infinity,
enabled: !!userUID,
onSuccess: (data) => {
queryClient.setQueryData('bookmark', data.bookmark)
queryClient.setQueryData('bookread', data.reading)
},
})
Currently start learning react-query from few days.
Any extra knowledge and functionality is highly acceptable and thanks in advance.
I want that when i manually changes cache data with queryClient.setQueryData it wil update the data state of react-query and make a re-render in the app.
2
Answers
i found a solution but I don't know it's a good way or not
You don’t need to create a separate query if there is no corresponding resource to cache. You can always just call
useQuery
again of theuserData
and then just use thebookMark
orbookRead
property of it. You can also compose hooks and use the select option:To address one of the comments:
This is wrong advice. Calling
queryClient.getQueryData
isn’t reactive, so your component will not re-render on its own if data in the cache changes. To get reactivity, you need theuseQuery
hook, because that’s what creates an observer.