反应阿波罗-突变时的奇怪效果? [英] React Apollo - Strange Effect When Making Mutation?

查看:67
本文介绍了反应阿波罗-突变时的奇怪效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用React-Apollo设置了一个React应用程序,并且可以成功查询我的API.

I've set up a React application with React-Apollo and can successfully query my API.

但是,当我进行突变时,会产生奇怪的效果.我已成功取回所有数据(如Chrome开发工具的网络"标签所示),但是当尝试console.log数据时,它表示是null.

However, when I make a mutation, a strange effect occurs. I get all the data back successfully (as seen in the Network tab of the Chrome Dev Tools), but when trying to console.log the data, it says that it is null.

以下是相关代码:

// mutation file

import gql from "graphql-tag";
export default gql`
  mutation CreateReservation($name: String!, $time: String!, $persons: String, $specialMessage: String, $email: String!) {
    createReservation(input: {
        name: $name,
        time: $time,
        persons: $persons,
        specialMessage: $specialMessage,
        email: $email
    }) {
        __typename
        error
        data
    }
  }
`;

// component file

import React from "react";
import {graphql, compose} from "react-apollo";
import CreateReservationMutation from "../../graphql/mutations/api/CreateReservation";

class Reservations extends React.Component {
testGraphQL = ({ reservationName, reservationTime, reservationEmail, reservationPartySize, reservationMessage}) => {

    const variables = {
        name: reservationName,
        time: reservationTime,
        persons: reservationPartySize,
        specialMessage: reservationMessage,
        email: reservationEmail
    };

    this.props.createReservation(variables)
    .then(({data}) => {
        console.log("Data received: ", data); // Here is the problem
    }).catch((err) => {
        console.log("Error sending data: ", err);
    })
}
render() {
    return (
        <div>
            ...
            <div>
                <Form 
                    ...
                    submitFunc={this.testGraphQL}
                />
            </div>
            ...
            </div>
        </div>
    )
  }
}

export default compose(
    graphql(CreateReservationMutation, {
        props: ({mutate}) => ({
            createReservation: (variables) => mutate({variables})
        })
    })
)(Reservations);

因此,当我调用testGraphQL函数时,我在控制台中收到以下消息:

So when I call the testGraphQL function, I receive the following in the console:

Data received:  {createReservation: null}

但是当在网络"选项卡中查看时,我发现数据实际上确实存在,并且正是我所要查找的.此外,我的数据库已使用所有保留详细信息正确更新,因此我可以肯定地知道正在执行该突变.

But when looking in the Network tab, I see that the data is actually there after all and is exactly what I am looking for. Furthermore, my database is correctly updated with all the reservation details, so I know with certainty that the mutation is being executed.

这是从网络"标签中看到的:

This is what I see from the Network tab:

{"data":{"createReservation":{"__typename":"ReservationResponse","error":null,"data":"Success"}}}

这就是我在testGraphQL中调用console.log时希望看到的.

That is what I expect to see when I call console.log in testGraphQL.

所以我知道我的架构,Apollo客户端或突变文件没有任何错误.

So I know that I don't have any errors with my schema, my Apollo Client, or my mutation file.

相反,问题必须出在我如何设置compose语句或如何调用突变本身上.

Instead, the problem has to lie with how I'm setting up my compose statement or with how I'm calling the mutation itself.

如果您在此处发现错误,请告诉我.谢谢

Please let me know if you spot the error here. Thank you

更新

我应该提到我正在使用AWS AppSync作为GraphQL提供程序.

I should mention that I am using AWS AppSync as my GraphQL provider.

该变异调用一个lambda函数,该函数执行以下操作:

The mutation calls a lambda function which does the following:

...
Promise.all([dynamodbPromise, snsPromise, sesPromise])
    .then((data) => {
        callback(null, {data: "Success"});
    })
    .catch((err) => {
        callback(null, {error: err});
    });

这是我针对此突变的解析器:

Here is my resolver for this mutation:

// request mapping template

{
  "version" : "2017-02-28",
  "operation": "Invoke",
  "payload": $util.toJson($ctx.args.input)
}

//  response mapping template

$util.toJson($context.result)

更新2

配置optimisticResonse并像这样重写我的突变:

Configuring an optimisticResonse and rewriting my mutation like this:

this.props.createReservation({
        variables,
        optimisticResponse: {
            createReservation: {
                __typename: "ReservationResponse",
                errorMessage: null,
                responseMessage: "_TEST_"
            }
        }
    })
    .then(res => {
        console.log("Apllo Data: ", res);
    })

导致我仅从乐观响应中获取数据,这是

Leads me to get only the data from the optimistic response, which is this:

{data:
  createReservation: {
    __typename: "ReservationResponse", 
    errorMessage: null, 
    responseMessage: "Optimistic Success"
}

因此返回的数据不得使用API​​的实际响应进行更新.

So the data returned must not be updated with the actual response from the API.

现在我该如何在返回乐观响应后强制Apollo更新响应?

How can I now force Apollo to update the response after returning the optimistic response?

推荐答案

您有两种选择来获取来自突变的数据响应:

You have two options to get the data response from a mutation:

在突变"组件中:

<Mutation>{mutation, {data}}</Mutation>

或在变异函数中:

mutate().then(data => ...)

您正在获得mutate promise响应,但是您希望apollo传递给Mutation组件的状态对象.

You are getting in the mutate promise response, but you are expecting the state object that apollo pass to the Mutation component.

阿波罗传递状态对象是没有意义的,因为如果成功解决了突变,则任何错误都会使诺言被拒绝,并且在mutate调用期间不会提供任何加载状态.

It doesn't make sense for apollo to pass the state object, because if the mutation resolved it was successful, any error will make the promise to be rejected and no loading state is provided during the mutate call.

因此,要修复您的代码,只需更改此内容

So to fix your code, you just need to change this

this.props.createReservation(variables)
    .then(data => {

这篇关于反应阿波罗-突变时的奇怪效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆