【问题标题】:AWS Appsync graphqlMutation helper not updating queryAWS Appsync graphqlMutation helper 不更新查询
【发布时间】:2019-08-09 09:16:37
【问题描述】:

我正在关注本教程:https://egghead.io/lessons/react-execute-mutations-to-an-aws-appsync-graphql-api-from-a-react-application

我有一个简单的 todo react 应用,通过放大连接到 AppSync。查询和突变由 Amplify 自动生成。

使用graphqlMutation 助手,我的查询应该在运行我的突变后自动更新,但它不起作用。刷新后,我确实看到突变正在更新 AppSync 后端,但我也希望它会立即更新并给出乐观的响应。

代码如下:

import React, { Component } from "react";
import gql from "graphql-tag";
import { compose, graphql } from "react-apollo";
import { graphqlMutation } from "aws-appsync-react";
import { listTodos } from "./graphql/queries";
import { createTodo, deleteTodo } from "./graphql/mutations";

class App extends Component {
  state = { todo: "" };

  addTodo = async () => {
    if (this.state.todo === "") {
      return;
    }

    const response = await this.props.createTodo({
      input: {
        name: this.state.todo,
        completed: false
      }
    });

    this.setState({ todo: "" });
    console.log("response", response);
  };

  deleteTodo = async id => {
    const response = await this.props.deleteTodo({ input: { id } });
    console.log("response", response);
  };

  render() {
    return (
      <div>
        <div>
          <input
            onChange={e => this.setState({ todo: e.target.value })}
            value={this.state.todo}
            placeholder="Enter a name..."
          />
          <button onClick={this.addTodo}>Add</button>
        </div>
        {this.props.todos.map(item => (
          <div key={item.id}>
            {item.name}{" "}
            <button onClick={this.deleteTodo.bind(this, item.id)}>
              remove
            </button>
          </div>
        ))}
      </div>
    );
  }
}

export default compose(
  graphqlMutation(gql(createTodo), gql(listTodos), "Todo"),
  graphqlMutation(gql(deleteTodo), gql(listTodos), "Todo"),
  graphql(gql(listTodos), {
    options: {
      fetchPolicy: "cache-and-network"
    },
    props: props => ({
      todos: props.data.listTodos ? props.data.listTodos.items : []
    })
  })
)(App);

包含代码库的 repo 在这里:https://github.com/jbrown/appsync-todo

我的查询没有更新,我做错了什么?

【问题讨论】:

    标签: javascript reactjs apollo-client aws-appsync appsync-apollo-client


    【解决方案1】:

    您的输入仅包含属性namecompleted。工具graphqlMutation会自动添加id

    代码不包含列表查询,我猜想查询请求的数据多于namecompletedid

    因此,由于缺少必需的信息,因此不会将项目添加到列表中。

    解决方案是将所有列出的属性添加到 createTodo。

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2019-12-11
      • 2019-02-04
      • 1970-01-01
      • 2021-01-29
      • 2019-02-25
      • 2019-01-18
      • 2019-05-03
      • 2019-09-03
      相关资源
      最近更新 更多