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

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

问题描述

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

但是,当我进行突变时,会出现奇怪的效果.我成功取回了所有数据(如 Chrome 开发工具的网络选项卡中所示),但是当尝试 console.log 数据时,它说它是 null.

相关代码如下:

//变异文件从graphql-tag"导入gql;导出默认 gql`突变 CreateReservation($name: String!, $time: String!, $persons: String, $specialMessage: String, $email: String!) {创建预订(输入:{名称:$名称,时间:$时间,人:$人,specialMessage: $specialMessage,电子邮件:$email}) {__类型名错误数据}}`;//组件文件从反应"导入反应;从react-apollo"导入 {graphql, compose};从../../graphql/mutations/api/CreateReservation"导入 CreateReservationMutation;类保留扩展 React.Component {testGraphQL =({reservationName,reservationTime,reservationEmail,reservationPartySize,reservationMessage})=>{常量变量 = {名称:预订名称,时间:预约时间,人:reservationPartySize,specialMessage:预订消息,邮箱:reservationEmail};this.props.createReservation(变量).then(({数据}) => {console.log("收到的数据:", data);//这里是问题}).catch((错误) => {console.log("发送数据出错:", err);})}使成为() {返回 (<div>...<div><表格...submitFunc={this.testGraphQL}/>

...

)}}导出默认撰写(graphql(CreateReservationMutation, {道具:({mutate}) =>({createReservation: (变量) =>变异({变量})})}))(预订);

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

收到的数据:{createReservation: null}

但是在查看网络"选项卡时,我发现数据实际上就在那里,而且正是我要查找的内容.此外,我的数据库已正确更新了所有预订详细信息,因此我确信正在执行更改.

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

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

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

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

相反,问题在于我如何设置我的 compose 语句或我如何调用突变本身.

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

更新

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

突变调用了一个执行以下操作的 lambda 函数:

<预><代码>...Promise.all([dynamodbPromise, snsPromise, sesPromise]).then((数据) => {回调(空,{数据:成功"});}).catch((错误) => {回调(空,{错误:错误});});

这是我对这个突变的解析器:

//请求映射模板{"版本": "2017-02-28","操作": "调用",有效载荷":$util.toJson($ctx.args.input)}//响应映射模板$util.toJson($context.result)

更新 2

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

this.props.createReservation({变量,乐观响应:{创建预订:{__typename: "预订响应",错误消息:空,响应消息:_TEST_"}}}).then(res => {console.log("阿普洛数据:", res);})

导致我只从乐观响应中获取数据,即:

{数据:创建预订:{__typename: "预订响应",错误消息:空,responseMessage:乐观的成功"}

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

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

解决方案

您有两种选择可以从突变中获取数据响应:

在 Mutation 组件中:

{mutation, {data}}

或者在变异函数中:

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

您收到了 mutate 承诺响应,但您期待的是 apollo 传递给 Mutation 组件的状态对象.

apollo 传递 state 对象没有意义,因为如果突变解决它成功,任何错误都会使承诺被拒绝,并且在 mutate 调用期间不提供加载状态.

所以要修复你的代码,你只需要改变这个

this.props.createReservation(变量).then(数据=> {

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

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.

Here's the relevant code:

// 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);

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"}}}

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

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

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

UPDATE

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

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)

UPDATE 2

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"
}

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

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:

In the Mutation component:

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

Or in the mutation function:

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

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

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 => {

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

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆