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
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With