Обновить кеш после мутации: свойство 'names' не существует для типа '{names: any; } | значение NULL'

Используя генератор кода GraphQL с React с хуками, я пытаюсь обновить кеш Apollo после мутации, следуя примеру в документации Apollo:

  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])},
      });
    },
  });

Однако я получаю Property 'names' does not exist on type '{ names: any; } | null'. на деструктурированной переменной запроса.

Что я делаю неправильно?

Заранее спасибо.

1 ответ

попробуй так

      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]
          }
        }
      })
    },
  });
Другие вопросы по тегам