I'm following this tutorial: https://egghead.io/lessons/react-execute-mutations-to-an-aws-appsync-graphql-api-from-a-react-application
I have a simple todo react app hooked up to AppSync via amplify. The queries and mutations were autogenerated by Amplify.
Using the graphqlMutation
helper, my query is supposed to be automatically updated after running my mutations, but it's not working. Upon refresh I do see the mutations are updating the AppSync backend, but I also expect it to update immediately with an optimistic response.
Here is the code:
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);
A repo containing the codebase is here: https://github.com/jbrown/appsync-todo
What am I doing wrong here that my query isn't updated?
Your input contains only properties
name
andcompleted
. ToolgraphqlMutation
will addid
automatically.Code doesn't contains list query, I can guess than query requested for more data than
name
,completed
andid
.So item will not be added to list because of missing required informations.
Solution is add all listed properties to createTodo.