I'm guessing this isn't an issue at all, but expected behavior, but wanted to double-check before adopting a different solution.
I have 2 components that render on the same page
<Navigation /> // 1st Component
<MainContent /> // 2nd Component
The 1st component makes a GraphQL Query to fetch the current user, adding the logged-in user to the Apollo Client cache. (In my ApolloClient the cache is using InMemoryCache)
const { data, loading } = useQuery(MeDocument);
The 2nd component is used to fetch the cached data to check if the user is logged in, without making the same redundant GraphQL query again.
import { useApolloClient } from '@apollo/client';
.....
const client = useApolloClient();
useEffect(() => {
console.log(client.cache.readQuery({ query: MeDocument })); // log is `null`
}, [client]);
However, the value from useApolloClient in the 2nd component doesn't update when the cache updates in the 1st component after the initial GraphQL Query completes. However, if I added a bit of a delay before reading the cache, or if the cache is read after a click event, or doing something like below, it does get the value, but this seems very hacky and unreliable.
useEffect(() => {
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
delay(300).then(() => console.log(client.cache.readQuery({ query: MeDocument }))); // log is not null
}, [client]);
I am guessing this is expected behavior, or is there a solution to this?
I was perhaps going to go down the route of adding the data property from the useQuery in the 1st component to update a redux reducer so that value can be consumed in the 2nd component. But was curious if this was possible without the need of a redux store?