Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. import React, { useReducer } from "react";
  2. import { useMutation } from "@apollo/react-hooks";
  3. const AddPost = () => {
  4. const ADD_POST = gql`
  5. mutation(
  6. $authorId: ID!
  7. $title: String!
  8. $body: String
  9. $isPublished: Boolean
  10. ) {
  11. addPost(
  12. data: {
  13. authorId: $authorId
  14. title: $title
  15. body: $body
  16. isPublished: $isPublished
  17. }
  18. ) {
  19. title
  20. body
  21. }
  22. }`;
  23. const [postState, setPostState] = useReducer(
  24. (state, newState) => ({ ...state, ...newState }),
  25. {
  26. title: "",
  27. body: ""
  28. }
  29. );
  30. const handleChange = e => {
  31. setPostState({ [e.target.name]: e.target.value });
  32. };
  33. const handleSubmit = e => {
  34. e.preventDefault();
  35. if (postState.title && postState.body) {
  36. console.log(postState, postState.body);
  37. addPost({
  38. variables: {
  39. ...postState,
  40. authorId: "5d6d364f1e13fe2d8fdc10b5",
  41. isPublished: true
  42. }
  43. });
  44. setPostState({ title: "", body: "" });
  45. } else alert("you have to provide data");
  46. };
  47. return (
  48. <div>
  49. <form onSubmit={handleSubmit}>
  50. <input
  51. type="text"
  52. value={postState.title}
  53. name="title"
  54. onChange={handleChange}
  55. />
  56. <br />
  57. <input
  58. type="text"
  59. value={postState.body}
  60. name="body"
  61. onChange={handleChange}
  62. />
  63. <br />
  64. <button>Publish</button>
  65. </form>
  66. </div>
  67. );
  68. };
  69.  
  70. export default AddPost;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement