Apollo-client: TypeError: Cannot assign to read only property

Created on 3 Feb 2020  路  5Comments  路  Source: apollographql/apollo-client

I'm keep getting this error

const { data, client } = useQuery(GET_GROUPS);
const onSkillSelect = id => {
  setSkill({ variables: { id, skills: props.skills } });
};

const toggleSwitch = () => {
  data.dataGroups[props.id].isSkillsDisabled = false;
  client.writeData({ data: data });
}

when i'm trying to mutate something from the cache.

Uncaught TypeError: Cannot assign to read only property 'isSkillsDisabled' of object '#<Object>

I'm using 3.0 beta client react

import { gql, useMutation, useQuery } from '@apollo/client';

any idea how to override the cache?

鉁嶏笍 working-as-designed

Most helpful comment

this should work:

const { data, client } = useQuery(GET_GROUPS);
const onSkillSelect = id => {
  setSkill({ variables: { id, skills: props.skills } });
};

const toggleSwitch = () => {
  const newDataGroups = [...data.dataGroups];
  newDataGroups[props.id] = { ...newDataGroups[props.id], isSkillsDisabled: false };
  const newData = { ...data, dataGroups: newDataGroups };
  client.writeData({ data: newData });
}

All 5 comments

This is intentional. Directly mutating the cache would often result in buggy behavior, so in v3 the cache is now readonly. If you need to change the data in the cache you will now need to make copies of your data before mutating.

this should work:

const { data, client } = useQuery(GET_GROUPS);
const onSkillSelect = id => {
  setSkill({ variables: { id, skills: props.skills } });
};

const toggleSwitch = () => {
  const newDataGroups = [...data.dataGroups];
  newDataGroups[props.id] = { ...newDataGroups[props.id], isSkillsDisabled: false };
  const newData = { ...data, dataGroups: newDataGroups };
  client.writeData({ data: newData });
}

The Apollo Client 2.6 blog post explains the benefits of immutability, and why it's becoming mandatory in Apollo Client 3.0: https://blog.apollographql.com/whats-new-in-apollo-client-2-6-b3acf28ecad1

any idea how to override the cache?

If your first instinct in response to an error like this is to "override" the library that's giving you the error, you're starting off on the wrong foot. Please try to understand what's going on first, or at least realize that the errors may be for your own good, before you jump to conclusions about possible workarounds. This issue tracker is for tracking bugs and features in the Apollo Client library, not a help desk for quick solutions to common problems that could be solved by reading the documentation on your own time.

it only happens in local develpment but not in prod. Is that intended as well?

You can use cloneDeep of loash to copy the result.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kriswep picture kriswep  路  3Comments

treecy picture treecy  路  3Comments

canercandan picture canercandan  路  3Comments

NeoPhi picture NeoPhi  路  3Comments

elie222 picture elie222  路  3Comments