sdy

make useMutation, onSubmit function

1 import React, { useState } from "react"; 1 import React, { useState } from "react";
2 -import { useQuery } from "@apollo/react-hooks"; 2 +import { useQuery, useMutation } from "@apollo/react-hooks";
3 import { withRouter } from "react-router-dom"; 3 import { withRouter } from "react-router-dom";
4 import RoomPresenter from "./RoomPresenter"; 4 import RoomPresenter from "./RoomPresenter";
5 -import { GET_ROOMS } from "./RoomQueries"; 5 +import { GET_ROOMS, CREATE_ROOM } from "./RoomQueries";
6 +import useInput from "../../Hooks/useInput";
7 +import { toast } from "react-toastify";
6 8
7 export default withRouter(() => { 9 export default withRouter(() => {
8 const [action, setAction] = useState("showList"); 10 const [action, setAction] = useState("showList");
9 11
12 + const roomName = useInput("");
13 +
10 const { data } = useQuery(GET_ROOMS); 14 const { data } = useQuery(GET_ROOMS);
11 - let roomArray; 15 + const [createRoom] = useMutation(CREATE_ROOM);
16 +
17 + let roomArray, newRoomObj;
12 if (data !== undefined) { 18 if (data !== undefined) {
13 const { getRooms } = data; 19 const { getRooms } = data;
14 roomArray = getRooms; 20 roomArray = getRooms;
15 } 21 }
22 +
23 + const onSubmit = async (e) => {
24 + e.preventDefault();
25 + if (roomName.value !== "") {
26 + try {
27 + newRoomObj = await createRoom({ variables: { name: roomName.value } });
28 + if (!newRoomObj) {
29 + // when fail to create room
30 + toast.error("fail to create new room");
31 + } else {
32 + // when success to make room
33 + toast.success("success to make new room !");
34 + setAction("showList");
35 + }
36 + } catch {
37 + toast.error("occur unexpected error");
38 + }
39 + } else {
40 + toast.error("room name is required !");
41 + }
42 + };
43 +
16 return ( 44 return (
17 <RoomPresenter 45 <RoomPresenter
18 roomArray={roomArray} 46 roomArray={roomArray}
19 action={action} 47 action={action}
20 setAction={setAction} 48 setAction={setAction}
49 + onSubmit={onSubmit}
50 + roomName={roomName}
21 /> 51 />
22 ); 52 );
23 }); 53 });
......