0

I'm new to Apollo and Apollo caching. I've been writing a demo project and have run into two issues:

  1. 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
});
  1. 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?

furnaceX
  • 567
  • 2
  • 8
  • 15
  • In Apollo client, when you refetch a query with same variable, sam query, Apollo will find data in its cache first, if it finds nothing, it will create a new request to fetch data from server. – Michael May 19 '20 at 04:05

1 Answers1

0

The Apollo GraphQL maintain the cache itself and certainly you don't have to -

export declare type FetchPolicy = 'cache-first' | 'network-only' | 'cache-only' | 'no-cache' | 'standby';

If you look into the fetchPolicy declaration then there are several options to do that -

  1. Network Only

    const { data } = useQuery(GET_LIST, {
    fetchPolicy: 'network-only'
    });
    
  2. Cache First

    const { data } = useQuery(GET_LIST, {
    fetchPolicy: 'cache-first'
    });
    
  3. Cache Only

    const { data } = useQuery(GET_LIST, {
    fetchPolicy: 'cache-only'
    });
    

Similarly the rest options also can be looked upon based on requirement.

If you want to maintain state and do that kinda work then write resolvers for those queries -

const client = new ApolloClient({
  uri: apollo.networkInterface,
  cache,
  resolvers: {
    Mutation: {
        searchQuery: (launch, _args, { cache }) => {
            console.log(cache); // cache can be queried here
            // read from cache if planning to modify the data
            //const { searchQuery } = cache.readQuery({ query: GET_LIST });
            cache.writeQuery({
                query: GET_LIST,
                data: {searchQuery:_args.searchQuery}
              });
          },
      },
  },
})

The Chrome client does work but for that the connection with the graphql server has to be done. Else it will not show up in chrome.

Dlucidone
  • 1,091
  • 9
  • 23