Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement