javascript "cannot add property" "object is not extensible" when I update cache in graphql query

Viewed 1359

How to update cache of graphql queries without an error?

const [ createBook ] = useMutation(CREATE_BOOK, {
    onError: (error) => {
      props.notify(error.message)
    }

    ,
    update: (store, response) => {
      console.log('-->', response.data.addBook)
      
      const dataInStore = store.readQuery({ query: ALL_BOOKS })

      console.log(dataInStore)
      dataInStore.allBooks.push(response.data.addBook)
      store.writeQuery({
        query: ALL_BOOKS,
        data: dataInStore
      })
      
    }
  })






console.log(dataInStore)

shows object with property Allbooks which is array to which I try to push

1 Answers

You should use spread syntax instead of push to update your cache.

Try this:

const [ createBook ] = useMutation(CREATE_BOOK, {
  onError: (error) => {
    props.notify(error.message)
  },
  update: (store, response) => {
    console.log('-->', response.data.addBook)
    const dataInStore = store.readQuery({ query: ALL_BOOKS })
    console.log(dataInStore)
    store.writeQuery({
      query: ALL_BOOKS,
      data: {
        ...dataInStore,
        allBooks: [...dataInStore.allBooks, response.data.addBook]
      }
    })

  }
})

console.log(dataInStore)

Related