I am putting queryClient.getQueryData
in dependency of useEffect hook to observer when data updating to cache but the useEffect never trigger update. What is the problem here?
My code below:
...
const queryClient = useQueryClient();
const queryKey = ['user', userId];
const userCache = queryClient.getQueryData(queryKey);
const [user, setUser] = useState(userCache || initialUserData);
// useEffect never trigger update even if userCache updated as new cache value
useEffect(() => {
if (!userCache) return;
setUser((prevUser) => ({ ...prevUser, ...userCache }));
console.log('this useEffect trigger update');
}, [userCache]);
return user;
queryClient.getQueryData
creates no subscription to the QueryCache - it just reads data once, whenever your component renders for another reason.
If you look at the docs, the correct way to setup a subscription and to have your component re-render whenever new data is written to the cache is via useQuery
.