0
votes

I'm using Apollo Dev Tools for Chrome and I can't seem to understand how to update the cache.

  1. The cache is the same after every query even though it's rendering the correct data.

  2. I'm developing a CRUD app and on a delete I want the page to show the changes made on the server. After executing a mutation that deletes an item in a DB I also want to delete this item from the cache.

    // mutation
    const DELETE_ELEMENT_MUTATION = gql`
      mutation DELETE_ELEMENT_MUTATION($id: String!) {
        deleteElement(id: $id)
      }
    `;
    
    // update cache
    update = (cache, payload) => {
      const data = cache.readQuery({query: queryAllElements});
      const result = data.allElements.filter(element => {
        const elementId = script._id;
        const compareId = JSON.parse(payload.data.deleteElement).id;
    
        return elementId !== compareId;
      });
    
      cache.writeQuery({query: queryAllElements, data: result});
    };
    
    <Mutation
      mutation={DELETE_ELEMENT_MUTATION}
      variables={{id: id}}
      update={this.update}
    >
      {(deleteElement) => (
        <Icon
          onClick={() => {
            deleteElement();
          }}
        />
      )}
    </Mutation>
    

After update the cache is not updating.

Edit: changed

cache.writeQuery({query: getAllElements, data: result}); 
// to 
cache.writeQuery({query: queryAllElements, data: result});
1
I'll try to do what is described in the issue. Meanwhile, I didn't think it's important at the time of writing the question by my <Mutation /> is a return from a <Query /> and was thinking maybe that's causing the problem?That Guy
Your read query is using "queryAllElements" and your write query is using "getAllElements"Benjamin Charais
My bad, I unintentionally did this when shrinking down the code to the smallest meaningful example. It's queryAllElements on both lines.That Guy

1 Answers

0
votes

I solved the problem. Turns out I was updating the wrong key in the cache.

solution