Search code examples
reactjsapolloreact-apolloapollo-client

How to force Apollo Client to use cached data for detail view page


I have a paginated cursor based query TODOS and detail page with query TODO to get data by ID. Whenever I go to detail view and use useQuery with TODO query (Which contains exactly same data as TODOS query result, it still tries to get data from server not from cache. How can I achieve to not get data from server (Because it already exists), I thought Apollo detect by id and return from the cache but no. Any suggestions ?

Similar issue as no this post, but I don't think thats a right approach, there should be better solution. (I hope)

This is TODOS query:

query TODOS(
  $paginationOptions: PaginationOptionsInput
) {
  todos(paginationOptions: $paginationOptions) {
    pagination {
      minCursor
      maxCursor
      sortOrder
      limit
      hasMoreResults
    }
    result {
     id
     ...SomeTodoFields
  }
}

And on detail page I have second query TODO

query (
  $todoId: String!
) {
  todo(todoId: $todoId) {
    id
    ...SomeTodoFields
  } 
}

Solution

  • Since I am using Apollo-client < 3.0 for me cacheRedirect worked fine, you can have a look farther here. Read every note carefully it is really important! My code example:

    cache: new InMemoryCache({
        fragmentMatcher,
        cacheRedirects: {
          Query: {
            todo: (_, args, { getCacheKey }) => {
              return getCacheKey({ __typename: 'TodoType', id: args.todoId })
            }
          }
        }
    
      })
    })
    

    Found some good relevant article as well, which you might want to check. This worked for me, hope it helps to someone else as well. :)