简体   繁体   中英

Using react-apollo (GraphQL) to do an insert mutation, how do I get the inserted id for the local store update?

I have form with the following submit handler, which then uses react-apollo's mutate method to send the GraphQL mutation:

const doSubmit = (values, { setSubmitting, setErrors }) => {
    //create a new obj: can't submit the extra stuff in values, GraphQL will yell at us!
    const newUser = {
        firstName: values.firstName,
        lastName: values.lastName,
        emailAddress: values.emailAddress,
        isActive: values.isActive,
        sharedAccount: values.sharedAccount,
        userId: values.userId
    };

    mutate({
        variables: { user: newUser },
        update: store => {
            //only update if adding a new user
            if (values.userId !== 0) {
                return;
            }
            let data = store.readQuery({ query: USER_LIST_QUERY });
            data.users.push(newUser);
            store.writeQuery({ query: USER_LIST_QUERY, data });
        }
    }).then(() => {
        //let formik know that submit is complete
        setSubmitting(false);
        //todo: redirect to userlist
    });
};

This approach is based on this mutate-with-update example in the docs .

I know that the mutate promise handler will have access to the inserted id because it will be returned in the graphql response, but that doesn't seem to be in time.

Unless I could have access to the store from that promise handler too, I don't see how this is possible. But it seems like such a common use case that there has to be a way, right? Am I missing something obvious?

The update method provides the updated object as the second parameter

update: (store, { ... access userId here ... }) => { ... }

From the docs :

This function will be called twice over the lifecycle of a mutation. Once at the very beginning if an optimisticResponse was provided. The writes created from the optimistic data will be rolled back before the second time this function is called which is when the mutation has succesfully resolved. At that point update will be called with the actual mutation result and those writes will not be rolled back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM