'Wrong ID gets passed from delete item Mutation

--- Update: Found the solution for this myself, posted an answer below ---

For my React Typescript project, with NestJS and Apollo GraphQL, I created a delete item mutation. That works fine, it deletes the correct item in the MongoDB database.

Only when I want to update the Apollo cache after the Mutation, without refetching the data, for some reason the wrong id get passed from the Mutation callback to the update function. It seem to be de id of last item of the array.

I made an example with id 62161412424edb0e850ce6a2 and added comments with the value of the id at that point in the code.

Does anyone know why this happens and how to fix it? If there are better methods to update the cache after a delete, with refetching data from the database, I would like to know that too.

The GraphQL mutation:

const DELETE_ITEM_BY_ID = gql`
  mutation deleteItemById ($id: ID!) {
    deleteItemById (
      input: { 
        id: $id
      }
    ) {
      id
    }
  }
`;

The Apollo hook:

const [mutationDeleteItemById] = useMutation(DELETE_ITEM_BY_ID, {update: updateCache});

The delete button, item ID is correct:

<button onClick={deleteItem(item.id)}>Delete</button> {/* // 62161412424edb0e850ce6a2 */}

The delete function, item ID is correct:

const deleteItem = (itemId:any) => (event: any) =>  {
  console.log(itemId); // 62161412424edb0e850ce6a2
  mutationDeleteItemById({
    variables: {
    id: itemId,
  }}); 
}

The UpdateCache function, item ID is incorrect. Is ID from other item:

const updateCache = (cache:any, data: any) => {
  console.log(data.data.deleteItemById.id); // 621611da424edb0e850ce69c - INCORRECT
};


Solution 1:[1]

I just found the answer myself. When deleting from the MongoDB the id property needed to be '_id' in the NestJs service. Thought 'id' was also accepted but that got ignored, did not raise an error, but the first item in the database gets deleted.

async deleteItemById(item: ItemInputId): Promise<Item>  {
  return this.itemModel.findOneAndDelete({_id: item.id}).exec();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PeterMoelker