简体   繁体   English

使用react-apollo(GraphQL)进行插入突变,如何获取本地商店更新的插入ID?

[英]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: 我有以下提交处理程序的形式,然后使用react-apollo的mutate方法发送GraphQL突变:

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 . 此方法基于docs中的此mutate-with-update示例

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. 我知道mutate promise处理程序将有权访问插入的id,因为它将在graphql响应中返回,但这似乎并不及时。

Unless I could have access to the store from that promise handler too, I don't see how this is possible. 除非我也可以从该Promise处理程序访问store ,否则我不知道这是怎么可能的。 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方法提供了更新的对象作为第二个参数

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. 从一开始就提供了optimisticResponse。 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. 届时将使用实际的突变结果调用更新,并且不会回退那些写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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