DEV Community

ogs
ogs

Posted on

The process of using Apollo Client from scratch and thinking of a better cache implementation.

1. When graphql doesn't need a cache.

Basically, it uses InMemoryCache in the first place, so by default it will be saved automatically.

const client = new ApolloClient({
  cache: new InMemoryCache({});
});
Enter fullscreen mode Exit fullscreen mode

I have not used the so-called cache control methods such as readQuery, readFragment, etc. much.
In fact, I was at a loss to figure out how to use this method successfully in a case where my app needed rich data binding.

2. Initially

I achieved my goal by putting data into useReactive and then updating this data cleanly when it changed.

const cache = useReactive(userCache);

// Updated...
const updatedUser = ...
userCache(cache, { ...updatedUser } ); // It's hardest when it's nested.
Enter fullscreen mode Exit fullscreen mode

However, it is a pain in the ass to change the data in this way. In the first place, there are so many times to change the data that it becomes a little difficult to handle. For example, graphql returns an array of data from related tables that are nested more than 5 layers deep, and it is stupid to change them honestly every time.

3. The next thing I thought of was refetch.

This is the most reliable method now, but the worst in terms of performance.

const { refetch } = useQuery(USER);

// Updated...
refetch().then();
Enter fullscreen mode Exit fullscreen mode

As before, we no longer have to foolishly update the data, we only have to throw another query to bring the data up to date.

4. In the end

I settled on caching the data in the InMemoryCache on initial load, and refetching the data with cache-only when updating the data.

initial load

const { loading, data } = useQuery(USER, {
  fetchPolicy: 'no-cache',
});
Enter fullscreen mode Exit fullscreen mode

updated

const { refetch } = useQuery(USER, {
  fetchPolicy: 'cache-only',
});

// Updated...
refetch().then();
Enter fullscreen mode Exit fullscreen mode

I don't know what approach I will change to in the future, as I am still working on Apollo currently. I'm still learning every day.
To be honest, I know that I should study the Fragment area properly, but I haven't been able to do so yet.

I'm happy to say that I've managed to avoid the worst case scenario of data inconsistency.

Finally

If anyone reading this knows of a better caching strategy for the Apollo Client, a good document (other than the official one), or an easy way to do it, I would be very happy to hear about it.

Top comments (0)