Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled Rejection (Error): Cannot assign to read only property 'getPosts' of object '#<Object>'

Tags:

reactjs

apollo

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 = '';
    },
  });
like image 619
Tim Bogdanov Avatar asked Oct 16 '20 21:10

Tim Bogdanov


2 Answers

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 = '';
    },
  });
like image 92
Tim Bogdanov Avatar answered Nov 13 '22 01:11

Tim Bogdanov


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 = "";
    },
  });
like image 7
Oshri Moalem Avatar answered Nov 13 '22 02:11

Oshri Moalem