2

Using GraphQL Code Generator with React with hooks, I'm trying to update the Apollo cache after a mutation, following the example in the Apollo docs:

  const [addName] = useAddNameMutation({
    update(cache, {data: {addName}}) {
      const {names} = cache.readQuery({query: GET_NAMES}); // Property 'names' does not exist on type '{ names: any; } | null'.
      cache.writeQuery({
        query: GET_NAMES,
        data: {names: names.concat([addName])},
      });
    },
  });

However, I get Property 'names' does not exist on type '{ names: any; } | null'. on the destructured query variable.

What am I doing wrong?

Thanks in advance.

lewislbr
  • 1,012
  • 14
  • 23

1 Answers1

0

try this way

const [addName] = useAddNameMutation({
    update(cache, {data: addName}) {
      cache.modify({
        fields: {
          names(existingNames = []) { // check if it is called 'names' in the Cache tab of Apollo Client dev tools in google chrome
            const newNameRef = cache.writeQuery({
              //query: GET_NAMES,
              query: GetNamesDocument, // assuming that your Query is called GetNames, and that in theory you would call it somewhere else like this: useGetNamesQuery()
              data: addName,
            })
            // return existingNames.concat(newNameRef) // if 'names' is a string, but I would think it's an array, then
            return [...existingNames, newNameRef]
          }
        }
      })
    },
  });