Skip to content

Commit

Permalink
Add new items
Browse files Browse the repository at this point in the history
  • Loading branch information
MrAlexLau committed Aug 8, 2020
1 parent 1a9c20d commit 0585a30
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/AddItem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React from "react";
import gql from "graphql-tag";
import { useMutation } from "@apollo/react-hooks";

const CREATE_ITEM = gql`
mutation CreateItem($data: ItemInput!) {
createItem(data: $data) {
_id
}
}
`;

const ITEMS_QUERY = gql`
{
allItems {
data {
_id
name
}
}
}
`;

export function AddItem() {
const [showForm, setShowForm] = React.useState(false);
const [newItemName, setNewItemName] = React.useState("");

const [createItem, { loading }] = useMutation(CREATE_ITEM, {
refetchQueries: [{ query: ITEMS_QUERY }],
onCompleted: () => {
setNewItemName("");
setShowForm(false);
},
});

if (showForm) {
return (
<form
onSubmit={(e) => {
e.preventDefault();
createItem({ variables: { data: { name: newItemName } } });
}}
>
<label>
<input
disabled={loading}
type="text"
value={newItemName}
onChange={(e) => setNewItemName(e.target.value)}
style={{ marginRight: "5px" }}
/>
</label>
<input disabled={loading} type="submit" value="Add" />
</form>
);
}

return <button onClick={() => setShowForm(true)}>Add Item</button>;
}
2 changes: 2 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import React from "react";
import { ApolloProvider } from "@apollo/client";
import { client } from "./client";
import { AddItem } from "./AddItem";
import { ItemList } from "./ItemList";

function App() {
return (
<ApolloProvider client={client}>
<div style={{ padding: "5px" }}>
<h3>My Todo Items</h3>
<AddItem />
<ItemList />
</div>
</ApolloProvider>
Expand Down

0 comments on commit 0585a30

Please sign in to comment.