Apollo Client Cache data may be lost when replacing

Viewed 469

I'm new at react, graphql and apollo world. I have a users paginated table that is working fine and have the edit and delete buttons in the grid. Edit is ok, but when I select delete a user button, user is removed from database (mongoDb) and it is also removed from the list, but I continue receiving this alert message:

Cache data may be lost when replacing the users field of a Query object.

To address this problem (which is not a bug in Apollo Client), define a custom merge function for the Query.users field, so InMemoryCache can safely merge these objects:

  existing: [{"__ref":"User:5fd1640bd374d210469efce9"},{"__ref":"User:5fd3a3ca7f8c0751ad7be34f"},{"__ref":"User:5fd3ce447f8c0751ad7be351"}]
  incoming: [{"__ref":"User:5fd1640bd374d210469efce9"},{"__ref":"User:5fd3ce447f8c0751ad7be351"}]

For more information about these options, please refer to the documentation:

  * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers
  * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects

My code for this mutation is :

  const [delUser] = useMutation(DELETE_USER, {
    update(proxy, result) {
      if (result) {
        showMessage({
          type: "success",
          title: "Message",
          message: "User deleted",
        });
        const data = proxy.readQuery({
          query: GET_USERS,
          variables: { take, skip, filter },
        });
        const newUsers = data.users.filter((u) => u.id !== selectedUser);
        const newData = { totalUsers: newUsers.length, users: newUsers };
        proxy.writeQuery({
          query: GET_USERS,
          variables: { take, skip, filter },
          data: newData,
        });
        setSelectedUser(null);
      }
    },
    onError(err) {
      setSelectedUser(null);
      setErrors(err.graphQLErrors[0].message);
    },
    variables: { id: selectedUser }
  });

How could I get rid of these alert if User objects already have IDs or how could I define a custom merge function if there is no specific fields for this object and I have already created a typePolicy for User, field Contacts as required in the edit user component? I also tried including a refetchQuery option.

0 Answers
Related