Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 623
3cirlces Avatar asked Jul 17 '20 22:07

3cirlces


People also ask

Can not add property object is not extensible?

To fix this error, you will either need to remove the call to Object. preventExtensions() entirely, or move it to a position so that the property is added earlier and only later the object is marked as non-extensible. Of course you can also remove the property that was attempted to be added, if you don't need it.

What is fetch policy in GraphQL?

Setting a fetch policyBy default, the useQuery hook checks the Apollo Client cache to see if all the data you requested is already available locally. If all data is available locally, useQuery returns that data and doesn't query your GraphQL server. This cache-first policy is Apollo Client's default fetch policy.


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)
like image 162
Michael Avatar answered Sep 30 '22 01:09

Michael