Categories
apollo reactjs

Unhandled Rejection (Error): Cannot assign to read only property ‘getPosts’ of object ‘#’

I’ve searched around the internet for a solution on this issue and have not come across one yet. I am creating a new post and adding it to the Apollo root query cache. for some reason even though newData returns a new object with the new query, it does not get assigned to the cache.

    const [createPost, { error }] = useMutation(CREATE_POST_MUTATION, {
variables: values,
update(proxy, result) {
const data = proxy.readQuery({
query: FETCH_POSTS_QUERY,
});
let newData = [...data.getPosts];
newData = [result.data.createPost, ...newData];
proxy.writeQuery({ query: FETCH_POSTS_QUERY, data: newData });
values.body = '';
},
});

you can do this :

  const [createPost, { error }] = useMutation(CREATE_POST, {
variables: formValues,
update(proxy, result) {
const data = proxy.readQuery({
query: FETCH_POSTS_QUERY,
});
proxy.writeQuery({
query: FETCH_POSTS_QUERY,
data: {
getPosts: [result.data.createPost, ...data.getPosts],
},
});
formValues.body = "";
},
});