Search code examples
javascriptgraphqlapollo-serverreact-apollo

How do I handle deletes in react-apollo


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?


Solution

  • 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);