Tdy
Tdy

Reputation: 1013

React Apollo Hooks - Chain mutations

I have two mutations:

My saveValue mutation requires a record ID. If I open my form on a new record, I don't have this ID yet, so on submit I need to call createRecord first to retrieve the ID and then saveValue to save values on my record.

This simple approach doesn't work:

const onSave = async values => {
    if (!recordId) {
         // Call createRecord to retrieve recordId (code is simplified here) 
         const recordId = await createRecord();
    }

    // Save my values
    return saveValue({variables: {recordId, values});
}

But I don't really know how should I deal with the loading and data of the first mutation and wait for it to run the second mutation.

Thanks!

Upvotes: 2

Views: 1443

Answers (2)

Alex Broadwin
Alex Broadwin

Reputation: 1338

The mutate function returns a promise that resolves to the mutation response data, so you should simply be able to use to achieve what you want.

From the source code:

If you're interested in performing some action after a mutation has completed, and you don't need to update the store, use the Promise returned from client.mutate

I'm not sure why this didn't work in your initial tests, but I tried it locally and it works as expected. You should essentially be able to do what you wrote in your question.

Upvotes: 3

skyboyer
skyboyer

Reputation: 23705

I'm not sure if there is a way to postpone execution(as well as we cannot pause <Mutation>). So how about moving second part into separate useEffect?

const [recordId, setRecordId] = useState(null);
const [values, setValues] = useState({});
const onSave = async _values => {
    if (!recordId) {
         // Call createRecord to retrieve recordId (code is simplified here) 
         setRecordId(await createRecord());
    }
    setValues(_values);
}
useEffect(() => {
  saveValue({variables: {recordId, values});
}, [recordId, _values]);

Another workaround is utilizing withApollo HOC:

function YourComponent({ client: { mutate } }) {
 onSave = async values => {
   let recordId;
   if (!recordId) {
     recordId = await mutate(createRecordQuery);
   }
   await mutate(saveValueQuery, values);
   // do something to let user know saving is done
 };

export withApollo(YourComponent);

Upvotes: 0

Related Questions