Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 280
derekdreery Avatar asked Nov 08 '16 10:11

derekdreery


People also ask

How do you delete Apollo cache?

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.

How do you update Apollo cache after mutation?

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.

How do you call a mutation in React?

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.


1 Answers

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); 
like image 137
vwrobel Avatar answered Oct 02 '22 18:10

vwrobel