Currently, we stumbled across a problem doing mutation in relay modern. We have a diary which contains many entries. Whenever user add a entry which day of diary doesn't exist, we also create a diary before create a entry. Everything works as expected but the UI doesn't update immediately after the mutations. Here's the code.
AddDiaryMutation
import { commitMutation, graphql } from 'react-relay';
const mutation = graphql`
mutation AddDiaryMutation($input: AddDiaryInput!) {
createDiary(input: $input) {
diary {
id
...EntryList_entries
}
}
}
`;
let clientMutationId = 0;
const commit = (environment, { date }, callback) =>
commitMutation(environment, {
mutation,
variables: {
input: {
date,
clientMutationId: clientMutationId++
}
},
onCompleted: response => {
const id = response.createDiary.diary.id;
callback(id);
}
});
export default { commit };
AddEntryMutation will get the id from AddDiaryMutation response to add entry.
import { commitMutation, graphql } from 'react-relay';
import { ConnectionHandler } from 'relay-runtime';
const mutation = graphql`
mutation AddEntryMutation($input: AddEntryInput!) {
createEntry(input: $input) {
entryEdge {
node {
id
project {
name
}
speaker {
name
}
}
}
}
}
`;
function sharedUpdater(store, diaryId, newEdge) {
const diaryProxy = store.get(diaryId);
const conn = ConnectionHandler.getConnection(diaryProxy,
'EntryList_entries');
ConnectionHandler.insertEdgeAfter(conn, newEdge);
}
let clientMutationId = 0;
const commit = (environment, { diaryId, ...rest }, callback) =>
commitMutation(environment, {
mutation,
variables: {
input: {
...rest,
clientMutationId: clientMutationId++
}
},
updater: store => {
const payload = store.getRootField('createEntry');
const newEdge = payload.getLinkedRecord('entryEdge');
sharedUpdater(store, diaryId, newEdge);
},
onCompleted: () => callback()
});
export default { commit };
EntryList fragment
fragment EntryList_entries on Diary {
entries(first: 20) @connection(key: "EntryList_entries", filters: [])
{
edges {
node {
...Entry_entry
}
}
}
}
Entry fragment
fragment Entry_entry on Entry {
id
project {
name
}
speaker {
name
}
}
1 Answer 1
I had issues with this updater also. I recommend console.log on every variable and see where the chain brakes. I have issues with my getConnection method (and i am changing my schema to include edges also). You can also console log the store from your environment to check the records there.
Comments
Explore related questions
See similar questions with these tags.