Hi Stephen,
Thanks for the comment!
I’m specifying the query like this:
import {gql} from "@apollo/client";
export const GET_ME = gql`
query GetMe {
me {
id
....
}
}
`;
and then using the query like this:
import React from "react"';
import {View} from "react-native";
import {useQuery} from "@apollo/client";
import {GetMe} from "graphql/generated";
const MyComponent: React.FC = () => {
const me = useQuery<GetMe>(GET_ME);
return (
<View>
...
</View>
);
}
I was not specifying a fetch policy as I believe that “cache-first” is the default. Since then I have tried setting it explicitly to “cache-first” but to no avail.
- You aren’t refreshing the page between query attempts, correct? (The cache does not persist across page loads unless you intentionally persist it)
I’m using apollo in react-native, so no page “refreshes”, no. I use this query in the “logged in” navigation stack component so that the data is preloaded. I then use the same query again in other components where I actually need the data.
I’ve wrapped the entire app in an “ApolloProvider” component so the cache should not be affected as I switch from the logged-out to the logged-in navigation stacks.
- Which version of
@apollo/client
are you using? I recommend using the latest version (currently 3.5.8
) to make sure the docs are in line with your app.
I’m currently on 3.5.5 of @apollo/client, but it’s a good shout - I’ll try updating to the latest.
What’s odd is I added a custom field policy to the to InMemoryCache to check that apollo is reading the field from the cache and it does indeed get hit:
export const apolloClient = new ApolloClient({
uri: API_CONFIG.baseUrl,
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
...
me: {
keyArgs: false,
read(existing, args) {
console.log("reading from cache", existing);
return existing;
}
},
},
},
},
}),
link: buildLink(),
});
I see the “reading from cache” in the logs.
I even went on to log “args.cache.extract()” inside of that field policy and I can see “me” and the associated user in the cache:
{
"ROOT_QUERY": {
"__typename": "Query",
...
"me": {
"__ref": "User:2"
}
...
},
}
"User:2": {
...
"__typename": "User",
"firstname": "Lee",
...
},
This is what the logs look like:
LOG reading from cache undefined
INFO Operation GetMe took 373ms to complete
LOG reading from cache {"__ref": "User:2"}
LOG reading from cache {"__ref": "User:2"}
INFO Operation GetMe took 65ms to complete
LOG reading from cache {"__ref": "User:2"}
So apollo performs the network request the first time, as the cached value is undefined, and caches the value ok. The second time the query is executed, “existing” does have the correct value which is returned from the read function.
It appears that apollo is determining that the returned value is not valid for the query? I’m, wondering if it’s something to do with there being no keyargs for this query?
Thanks again for getting back to me, and apologies for the wall of text!
Lee