How to best use ApolloClient / InMemoryCache and enable Cache on demand for API's?

Viewed 332

I want to refractor the current code to use the ApolloClient constructor to cache information and only query for new data if the requesting data isn't already cache –

Currently I'm using fetchPolicy to cache users Id but from what I've seen there is a way to cache using apollo.

async fetchRecipients(userIds: string[]) {

  //TODO: How to refactor and use apollo cache?

  const result = await client?.query({
    query: MembersBySFIDs,
    variables: {sfids: userIds},
    fetchPolicy: 'cache-first',
  });

  if (result?.data?.membersBySFIDs) {
    await dispatch.newChatMessage.setRecipients(result.data.membersBySFIDs);
  } else {
    throw new Error('Members not found');
  }
}

Here is what I tried so far, I don't think I am using it correctly, any help is appreciated:

import { InMemoryCache, ApolloClient } from '@apollo/client';

const result = new ApolloClient({
  cache: new InMemoryCache()
});

async fetchRecipients(userIds: string[]) {
  const result = await client?.query({
    query: MembersBySFIDs,
    variables: {sfids: userIds},
    fetchPolicy: 'cache-and-network'
  });

  if (result?.data?.membersBySFIDs) {
    await dispatch.newChatMessage.setRecipients(result.data.membersBySFIDs);
  } else {
    throw new Error('Members not found');
  }
}
1 Answers

You can set the default behavior of client.query by configuring ApolloClient's the default fetchPolicy to cache-first in defaultOptions as shown here.

Something like this:

import { InMemoryCache, ApolloClient } from '@apollo/client';

const client = new ApolloClient({
  cache: new InMemoryCache(),
  defaultOptions: {
    query: {
      fetchPolicy: "cache-first"
    }
  }
});


async fetchRecipients(userIds: string[]) {
  const result = await client?.query({
    query: MembersBySFIDs,
    variables: {sfids: userIds},
  });

  // do whatever you want with the result here
 
}

Hope you found this helpful.

Related