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 = '';
},
});
After just a bit of posting this question, I figured it out. Looking over the apollo writeQuery docs I noticed that you must make a copy of each state.
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: {
...data,
getPosts: {
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 = "";
},
});
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