当我在graphql查询中更新缓存时,javascript“无法添加属性”“对象不可扩展”

3ci*_*ces 5 graphql apollo-client

如何在没有错误的情况下更新graphql查询的缓存?

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)
Run Code Online (Sandbox Code Playgroud)

显示具有属性 Allbooks 的对象,这是我尝试推送到的数组

Mic*_*ael 4

您应该使用spread syntax而不是push更新您的缓存。

尝试这个:

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)
Run Code Online (Sandbox Code Playgroud)