I'm new to Apollo and Apollo caching. I've been writing a demo project and have run into two issues:
- Can't get
cacheRedirects
to work properly:
In my demo, I "Load All" COVID19 test data, which queries an API and returns an array of results for 3 countries, including Canada. Then I try to load an individual result ("Load Canada") to get it to use my cacheRedirects
resolver. I think I have this set up correctly, but it always goes back to the API to do the query rather than reading from the cache.
Here is my Apollo client with cache:
const client = new ApolloClient({
uri: "https://covid19-graphql.now.sh",
cache: new InMemoryCache({
dataIdFromObject: obj => {
console.log("in cache: obj:", obj);
let dataId = null;
switch (obj.__typename) {
case "Country":
dataId = obj.__typename + "_" + obj.name;
break;
default:
dataId = defaultDataIdFromObject(obj);
}
console.log("in cache: dataId:", dataId);
return dataId;
},
cacheRedirects: {
Query: {
country: (_, args, { getCacheKey }) => {
console.log("in cacheRedirects:", _, args);
const cacheKey = getCacheKey({ __typename: "Country", ...args });
console.log("cacheKey:", cacheKey);
return cacheKey;
}
}
}
})
// connectToDevTools: true
});
- I can't figure out how to perform a
readFragment
:
I've tried so many different configurations within this code, but I never get any results.
Here is my function:
const ReadFragment = () => {
console.log("in ReadFragment");
try {
const data = client.readFragment({
id: GET_DATA.countryData,
fragment: gql`
fragment mostRecent on country {
id
text
complete
}
`
});
if (data) {
console.log(data);
return (
<div>
From Fragment: {JSON.stringify(data)}
</div>
);
} else {
return <div>From Fragment: not found</div>;
}
} catch (error) {
// console.error(error);
return <div>From Fragment: not found</div>;
}
};
Bonus Question: I don't seem to be able to get the Apollo Client Developer Tools extension to work in Chrome browser. Does this still work? My code never seems to connect to it. (uncomment out the connectToDevTools: true
.) It seems that being able to examine the contents of the cache would be very useful for development and learning. Is there an alternate way to view the cache contents?