1

我正在关注本教程: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

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

4

1 回答 1

0

您的输入仅包含属性namecompleted. 工具graphqlMutationid自动添加。

代码不包含列表查询,我可以猜到查询请求的数据多于name,completedid.

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

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

于 2019-05-15T11:33:52.230 回答