ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 1-6 비동기 통신 - axios(post,delete,patch)
    React 심화주차 2023. 5. 15. 14:56

    post: 데이터를 추가하는 방식(보통 input창을 이용)

    input에 들어오는 데이터를 감지하려고 value와 onChange를 엮어줬다.

    db.json과 같은 json기반 no-sql방식(몽고DB등)의 id속성은 자동으로 입력된다.
    그러므로 const [inputValue, setInputValue] = useState[{
        title: ''
      }] 안에 들어가는 객체에 id를 따로 넣지 않아도 된다.

    import { useEffect } from "react";
    import "./App.css";
    import axios from "axios";
    import { useState } from "react";
    
    function App() {
      const [todos, setTodos] = useState(null);
      const [inputValue, setInputValue] = useState({
        title: "",
      });
    
      const fetchTodos = async () => {
        const { data } = await axios.get("http://localhost:5000/todos");
        console.log("data", data);
        setTodos(data);
      };
    
      const onSubmitHandler = async () => {
        axios.post("http://localhost:5000/todos", inputValue);
        setTodos([...todos, inputValue]);
      };
    
      useEffect(() => {
        //최초 마운트 시점에서 db로부터 값을 가져오기. 그러기위해서는 위에서 비동기함수를 하나 생성한다.
        fetchTodos();
      }, []);
    
      return (
        <>
          <div>
            {/* input영역 */}
            <form
              onSubmit={(e) => {
                e.preventDefault();
                onSubmitHandler();
                //버튼 클릭시, input에 들어있는 값(state)을 이용하여 DB에 저장(post요청)
              }}
            >
              <input
                type="text"
                value={inputValue.title}
                onChange={(e) => {
                  setInputValue({
                    title: e.target.value,
                  });
                }}
              />
    
              <button type="submit">추가</button>
            </form>
          </div>
          <div>
            {/* data영역 */}
            {todos?.map((item) => {
              return (
                <div key={item.id}>
                  {item.id} : {item.title}
                </div>
              );
            })}
          </div>
        </>
      );
    }
    
    export default App;



    삭제하기
    삭제 함수를 
    onClick={}버튼과 엮어줄때
    onDeleteButtonClickHandler는 async함수를 이용했기때문에
    item.id라는 인자를 보낼때는 꼭 ()=>를 넣은 후에 버튼을 엮어줘야한다.
    실시간으로 삭제가 되게 하기위해서 state를 추가해서 바로바로 리렌더링되도록 해준다.

    import { useEffect } from "react";
    import "./App.css";
    import axios from "axios";
    import { useState } from "react";
    
    function App() {
      const [todos, setTodos] = useState(null);
      const [inputValue, setInputValue] = useState({
        title: "",
      });
    
      const fetchTodos = async () => {
        const { data } = await axios.get("http://localhost:5000/todos");
        console.log("data", data);
        setTodos(data);
      };
    
      const onSubmitHandler = async () => {
        axios.post("http://localhost:5000/todos", inputValue);
        setTodos([...todos, inputValue]);
      };
    
      const onDeletButtonClickHandler = async (id) => {
        axios.delete(`http://localhost:5000/todos/${id}`);
        setTodos(
          todos.filter((item) => {
            return item.id !== id;
          })
        );
      };
    
      useEffect(() => {
        //최초 마운트 시점에서 db로부터 값을 가져오기. 그러기위해서는 위에서 비동기함수를 하나 생성한다.
        fetchTodos();
      }, []);
    
      return (
        <>
          <div>
            {/* input영역 */}
            <form
              onSubmit={(e) => {
                e.preventDefault();
                onSubmitHandler();
                //버튼 클릭시, input에 들어있는 값(state)을 이용하여 DB에 저장(post요청)
              }}
            >
              <input
                type="text"
                value={inputValue.title}
                onChange={(e) => {
                  setInputValue({
                    title: e.target.value,
                  });
                }}
              />
    
              <button type="submit">추가</button>
            </form>
          </div>
          <div>
            {/* data영역 */}
            {todos?.map((item) => {
              return (
                <div key={item.id}>
                  {item.id} : {item.title}
                  &nbsp;
                  <button onClick={() => onDeletButtonClickHandler(item.id)}>
                    삭제
                  </button>
                </div>
              );
            })}
          </div>
        </>
      );
    }
    
    export default App;



    수정하기

    import { useEffect } from "react";
    import "./App.css";
    import axios from "axios";
    import { useState } from "react";
    
    function App() {
      const [todos, setTodos] = useState(null);
      const [inputValue, setInputValue] = useState({
        title: "",
      });
      const [targetId, setTargetId] = useState("");
      const [contents, setContents] = useState("");
    
      const fetchTodos = async () => {
        const { data } = await axios.get("http://localhost:5000/todos");
        console.log("data", data);
        setTodos(data);
      };
    
      // 추가 함수
      const onSubmitHandler = async () => {
        axios.post("http://localhost:5000/todos", inputValue);
        setTodos([...todos, inputValue]);
      };
    
      // 삭제 함수
      const onDeletButtonClickHandler = async (id) => {
        axios.delete(`http://localhost:5000/todos/${id}`);
        setTodos(
          todos.filter((item) => {
            return item.id !== id;
          })
        );
      };
    
      // 수정 함수
      const onUpdateButtonClickHandler = async () => {
        axios.patch(`http://localhost:5000/todos/${targetId}`, {
          title: contents,
        });
    
        setTodos(
          todos.map((item) => {
            if (item.id == targetId) {
              return { ...item, title: contents };
            } else {
              return item;
            }
          })
        );
      };
    
      useEffect(() => {
        //최초 마운트 시점에서 db로부터 값을 가져오기. 그러기위해서는 위에서 비동기함수를 하나 생성한다.
        fetchTodos();
      }, []);
    
      return (
        <>
          <div>
            {/* 수정영역 */}
            <input
              type="text"
              placeholder="아이디 입력"
              value={targetId}
              onChange={(e) => {
                setTargetId(e.target.value);
              }}
            />
            <input
              type="text"
              placeholder="수정할 내용 입력"
              value={contents}
              onChange={(e) => {
                setContents(e.target.value);
              }}
            />
            <button onClick={onUpdateButtonClickHandler}>수정</button>
            <br />
            <br />
          </div>
          <div>
            {/* input영역 */}
            <form
              onSubmit={(e) => {
                e.preventDefault();
                onSubmitHandler();
                //버튼 클릭시, input에 들어있는 값(state)을 이용하여 DB에 저장(post요청)
              }}
            >
              <input
                type="text"
                value={inputValue.title}
                onChange={(e) => {
                  setInputValue({
                    title: e.target.value,
                  });
                }}
              />
    
              <button type="submit">추가</button>
            </form>
          </div>
          <div>
            {/* data영역 */}
            {todos?.map((item) => {
              return (
                <div key={item.id}>
                  {item.id} : {item.title}
                  &nbsp;
                  <button onClick={() => onDeletButtonClickHandler(item.id)}>
                    삭제
                  </button>
                </div>
              );
            })}
          </div>
        </>
      );
    }
    
    export default App;



    *추가버튼을 눌렀을 때 오류가 떴던 이유는 
     // 추가 함수
      const onSubmitHandler = async () => {
        axios.post("http://localhost:5000/todos", inputValue);
        setTodos([...todos, inputValue]);
      };
    를 하면 우리가 정의한 todos에는 따로 id를 지정하지 않았기 때문에 값이 바로 들어오지 않고
    새로고침해야 DB에서 지정해줬던 방식이었기 때문이었다.
    그러므로 setTodos([...todos, inputValue])보다 

    const fetchTodos = async () => {
        const { data } = await axios.get("http://localhost:5000/todos");
        console.log("data", data);
        setTodos(data);
      };
    에서 그려주는 DB데이터를 바로 사용하게되면 오류가 뜨지 않게된다.

    import { useEffect } from "react";
    import "./App.css";
    import axios from "axios";
    import { useState } from "react";
    
    function App() {
      const [todos, setTodos] = useState(null);
      const [inputValue, setInputValue] = useState({
        title: "",
      });
      const [targetId, setTargetId] = useState("");
      const [contents, setContents] = useState("");
    
      const fetchTodos = async () => {
        const { data } = await axios.get("http://localhost:5000/todos");
        console.log("data", data);
        setTodos(data);
      };
    
      // 추가 함수
      const onSubmitHandler = async () => {
        axios.post("http://localhost:5000/todos", inputValue);
        // setTodos([...todos, inputValue]);
        fetchTodos();
      };
    
      // 삭제 함수
      const onDeletButtonClickHandler = async (id) => {
        axios.delete(`http://localhost:5000/todos/${id}`);
        setTodos(
          todos.filter((item) => {
            return item.id !== id;
          })
        );
      };
    
      // 수정 함수
      const onUpdateButtonClickHandler = async () => {
        axios.patch(`http://localhost:5000/todos/${targetId}`, {
          title: contents,
        });
    
        setTodos(
          todos.map((item) => {
            if (item.id == targetId) {
              return { ...item, title: contents };
            } else {
              return item;
            }
          })
        );
      };
    
      useEffect(() => {
        //최초 마운트 시점에서 db로부터 값을 가져오기. 그러기위해서는 위에서 비동기함수를 하나 생성한다.
        fetchTodos();
      }, []);
    
      return (
        <>
          <div>
            {/* 수정영역 */}
            <input
              type="text"
              placeholder="아이디 입력"
              value={targetId}
              onChange={(e) => {
                setTargetId(e.target.value);
              }}
            />
            <input
              type="text"
              placeholder="수정할 내용 입력"
              value={contents}
              onChange={(e) => {
                setContents(e.target.value);
              }}
            />
            <button onClick={onUpdateButtonClickHandler}>수정</button>
            <br />
            <br />
          </div>
          <div>
            {/* input영역 */}
            <form
              onSubmit={(e) => {
                e.preventDefault();
                onSubmitHandler();
                //버튼 클릭시, input에 들어있는 값(state)을 이용하여 DB에 저장(post요청)
              }}
            >
              <input
                type="text"
                value={inputValue.title}
                onChange={(e) => {
                  setInputValue({
                    title: e.target.value,
                  });
                }}
              />
    
              <button type="submit">추가</button>
            </form>
          </div>
          <div>
            {/* data영역 */}
            {todos?.map((item) => {
              return (
                <div key={item.id}>
                  {item.id} : {item.title}
                  &nbsp;
                  <button onClick={() => onDeletButtonClickHandler(item.id)}>
                    삭제
                  </button>
                </div>
              );
            })}
          </div>
        </>
      );
    }
    
    export default App;

    'React 심화주차' 카테고리의 다른 글

    1-8 axios interceptor  (0) 2023.05.16
    1-7 axios와 fetch의 비교  (0) 2023.05.15
    1-5 비동기 통신 - axios(get)  (0) 2023.05.15
    1-4 json-server  (0) 2023.05.13
    1-3 json-server  (1) 2023.05.13
Designed by Tistory.