Updating Apollo Cache - React Native

Hi,

I’m using Hasura, RN, Apollo Client with InMemoryCache.

I’m using React Navigation. I have a tab bar + stack navigation.

In one of my pages inside the stack navigation, I’m using mutation and I’m fetching the as a return value.

Once the mutation completes and when I navigate back to the main tab bar page; the data seems not updated.

I tried to use update from useMutation to update the cache, but it seems I don’t actually need that because once I print the cache after mutation, it seems it is updated.

I don’t think I need to refetch(), refetchQueries() etc. I believe the cache update should be reflected in my views.

Where do you think the problem can be?

Hi @cononymous, welcome to the forum! By any chance, are the fields you’re trying update part of a list?

1 Like

Yes, they’re.

Let me explain in another way, with an example:

I’m fetching the list of books on screen X.

const FETCH_BOOKS = gql`
  query fetchBooks {
    books { id }
  }`
const { data } = useQuery(FETCH_BOOKS);

If the user clicks to add a new book, screen Y opens, and the user adds a new book to the database.

const ADD_BOOK = gql`
  mutation addBook(...) {
    id
  }`
await useMutation(ADD_BOOK);

In this case, I’m expecting that ApolloCache should be updated but when I go back from screen Y to screen X, screen X does not show the newly added data.

Thanks for that additional detail @cononymous :pray: It looks like the books field is a list. Per the docs:

[…] a newly cached object isn’t automatically added to any list fields that should now include that object. To accomplish this, you can define an update function.

So even though the added book has an entry in the cache, there’s no reference to it in your books list. I hope that helps narrow things down, let me know how we can help further :slight_smile: