Skip to content

Instantly share code, notes, and snippets.

@danielfttorres
Last active November 1, 2017 17:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielfttorres/b88086d7f3e48c64518d4861f4ab43ee to your computer and use it in GitHub Desktop.
Save danielfttorres/b88086d7f3e48c64518d4861f4ab43ee to your computer and use it in GitHub Desktop.
Some stuff for help to make Relay Modern mutation updates
// @flow
import Relay, { graphql } from 'react-relay'
import { mutationCreateUpdater} from './mutationUpdater'
const mutation = graphql`
mutation createStoryMutation($input: CreateStoryInput!) {
createStory(input: $input) {
story {
id
title
author
}
}
}
`
const variables = {
input: {
story: {
title: 'My first story',
author: 'Daniel'
}
}
}
/*
const configs = [{
type: 'RANGE_ADD',
parentID: 'client:root:viewer',
connectionInfo: [{
key: 'ViewerQuery_stories',
rangeBehavior: 'append',
}],
edgeName: 'storyEdge'
}]
*/
const updater = mutationCreateUpdater('createStory', 'story', 'ViewerQuery_stories')
Relay.commitMutation(environment,
{
mutation,
variables,
updater: updater,
optimisticUpdater: updater,
onCompleted: res => console.info(res),
onError: err => console.error(err),
}
)
// @flow
import { ConnectionHandler } from 'relay-runtime'
const sharedUpdater = (store, mutationName, modelName, connectionName) => {
const payload = store.getRootField(mutationName)
const model = payload.getLinkedRecord(modelName)
if (!model) {
console.error('Could not find getLinkedRecord from mutation payload with name: ' + modelName)
return
}
const parentID = store.get('client:root') // can also be 'viewer' or 'client:root:viewer'
const connection = ConnectionHandler.getConnection(parentID, connectionName)
return { connection, model }
}
export const mutationCreateUpdater = function(mutationName, modelName, connectionName) {
return (store) => {
const { connection, model } = sharedUpdater(store, mutationName, modelName, connectionName)
const newEdge = ConnectionHandler.createEdge(store, connection, model, modelName+'Edge')
ConnectionHandler.insertEdgeAfter(connection, newEdge)
}
}
export const mutationDeleteUpdater = function(mutationName, modelName, connectionName) {
return (store) => {
const { connection, model } = sharedUpdater(store, mutationName, modelName, connectionName)
ConnectionHandler.deleteNode(connection, model.getValue('id'))
}
}
@danielfttorres
Copy link
Author

Under development

Based on: facebook/relay#2157

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment