I have a mutation like
mutation deleteRecord($id: ID) { deleteRecord(id: $id) { id } }
and in another location I have a list of elements.
Is there something better I could return from the server, and how should I update the list?
More generally, what is best practice for handling deletes in apollo/graphql?
When we have access to the cache object we can call cache. data. delete(key) where key is the key that Apollo is using to store the data for a specific item. And the record will be entirely deleted from the cache.
If a mutation updates a single existing entity, Apollo Client can automatically update that entity's value in its cache when the mutation returns. To do so, the mutation must return the id of the modified entity, along with the values of the fields that were modified.
For mutations, the graphql HOC passes down a mutate prop, which we'll call to execute the mutation. import React from 'react'; import { gql, graphql } from 'react-apollo';const AddChannel = ({ mutate }) => { const handleKeyUp = (evt) => { if (evt. keyCode === 13) { evt. persist(); mutate({ variables: { name: evt.
I am not sure it is good practise style but here is how I handle the deletion of an item in react-apollo with updateQueries:
import { graphql, compose } from 'react-apollo'; import gql from 'graphql-tag'; import update from 'react-addons-update'; import _ from 'underscore'; const SceneCollectionsQuery = gql ` query SceneCollections { myScenes: selectedScenes (excludeOwner: false, first: 24) { edges { node { ...SceneCollectionScene } } } }`; const DeleteSceneMutation = gql ` mutation DeleteScene($sceneId: String!) { deleteScene(sceneId: $sceneId) { ok scene { id active } } }`; const SceneModifierWithStateAndData = compose( ..., graphql(DeleteSceneMutation, { props: ({ mutate }) => ({ deleteScene: (sceneId) => mutate({ variables: { sceneId }, updateQueries: { SceneCollections: (prev, { mutationResult }) => { const myScenesList = prev.myScenes.edges.map((item) => item.node); const deleteIndex = _.findIndex(myScenesList, (item) => item.id === sceneId); if (deleteIndex < 0) { return prev; } return update(prev, { myScenes: { edges: { $splice: [[deleteIndex, 1]] } } }); } } }) }) }) )(SceneModifierWithState);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With