Created
October 2, 2019 14:46
-
-
Save cziem/759ebdde228d28ffbfad4c44bf8b3891 to your computer and use it in GitHub Desktop.
Create a new post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer } from "react"; | |
import { useMutation } from "@apollo/react-hooks"; | |
const AddPost = () => { | |
const ADD_POST = gql` | |
mutation( | |
$authorId: ID! | |
$title: String! | |
$body: String | |
$isPublished: Boolean | |
) { | |
addPost( | |
data: { | |
authorId: $authorId | |
title: $title | |
body: $body | |
isPublished: $isPublished | |
} | |
) { | |
title | |
body | |
} | |
}`; | |
const [postState, setPostState] = useReducer( | |
(state, newState) => ({ ...state, ...newState }), | |
{ | |
title: "", | |
body: "" | |
} | |
); | |
const handleChange = e => { | |
setPostState({ [e.target.name]: e.target.value }); | |
}; | |
const handleSubmit = e => { | |
e.preventDefault(); | |
if (postState.title && postState.body) { | |
console.log(postState, postState.body); | |
addPost({ | |
variables: { | |
...postState, | |
authorId: "5d6d364f1e13fe2d8fdc10b5", | |
isPublished: true | |
} | |
}); | |
setPostState({ title: "", body: "" }); | |
} else alert("you have to provide data"); | |
}; | |
return ( | |
<div> | |
<form onSubmit={handleSubmit}> | |
<input | |
type="text" | |
value={postState.title} | |
name="title" | |
onChange={handleChange} | |
/> | |
<br /> | |
<input | |
type="text" | |
value={postState.body} | |
name="body" | |
onChange={handleChange} | |
/> | |
<br /> | |
<button>Publish</button> | |
</form> | |
</div> | |
); | |
}; | |
export default AddPost; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment