Notice
Recent Posts
Recent Comments
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

HYEWON JUNG의 개발일지

axios get post delete patch 본문

React

axios get post delete patch

혜won 2023. 11. 29. 10:23

axios란?

간단히  http를 이용해 서버와 통신하기 위해 사용하는 패키지

axios 설치 방법

yarn add axios

 

json-server로 만들어 놓은 데이터를 get 해오는데 response로 그대로 받아서 콘솔에 찍어보면

const fetchTodos = async () => {
    const response = await axios.get("http://localhost:4000/todos");
    console.log("response=>", response);
  };
  useEffect(() => {
    fetchTodos();
  });

이런식으로 나온다. 여기서 우리가 사용할 곳은 data 부분이다

 

만약 비동기 처리를 해주지 않는다면

데이터가 담기지 않은 채로 콘솔이 찍히게 된다.

우리가 필요한 data 부분을 구조분해 할당으로 빼내면

필요한 부분이 나오는 것을 볼 수 있다. 

 

이 데이터를 화면에 뿌려주려면 이젠 익숙한 map을 돌려줘야한다. 

 <div>
      {todos.map((todo) => {
        return (
          <div key={todo.id}>
            {todo.id}:{todo.title}
          </div>
        );
      })}
    </div>

이럴 경우에 이미 첫 렌더링이 되어있는 상태에선 오류가 안날지 몰라도 새로고침을 하는 순간 오류가 발생할 것이다 .

이제 너무 자주봐서 질리는 오류인

Uncaught TypeError: Cannot read properties of null (reading 'map')

이 오류를 마주할 것이다. 

 

그 이유는 위에서는 비동기적으로 기다리지만  밑에  jsx부분은 기다리지 않고 바로 파싱되기때문에 데이터가 불러와지지 않았어도 작동을 하려하기 때문이다. 그래서 그 문제를 해결하기 위해서 optional chaining을 사용해 줄 것이다. 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Optional_chaining

 

Optional chaining - JavaScript | MDN

optional chaining 연산자 (?.) 는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다.

developer.mozilla.org

optional chaining의 사용법은 정말 간단하다

<div>
      {todos?.map((todo) => {
        return (
          <div key={todo.id}>
            {todo.id}:{todo.title}
          </div>
        );
      })}
    </div>

todos.map 이 아니라 todos?.map으로 작성해주면 된다. 

하지만 이렇게만 하면 화면에 읽히지 않는 것은 당연하다. 

  const [todos, setTodos] = useState(null);

  const fetchTodos = async () => {
    const { data } = await axios.get("http://localhost:4000/todos");
    setTodos(data);
  };
  useEffect(() => {
    fetchTodos();
  }, []);

set을 해주지 않았기 때문이다. 

 

이제 글을 추가하는 로직을 작성해보자

axios에서 데이터 추가는  post 이다. 

  const [inputValue, setInputValue] = useState({
    title: "",
  });

const addTodoHandler = async () => {
    axios.post("http://localhost:4000/todos", inputValue);

  };

작성방식은 get과 유사하지만 inputValue를 넣어준다는 것이 다르다. 

그리고 화면에 바로 적용될 수 있도록 set을 해줘야 하는데 

  const addTodoHandler = async () => {
    axios.post("http://localhost:4000/todos", inputValue);
    setTodos([...todos, inputValue]);
  };

단순히 이렇게만 하게 되면 자동으로 부여되는 id는 바로 뜨지 않고 새로고침을 해야 뜨게 된다. 그래서 이럴 땐 그냥 

  const addTodoHandler = async () => {
    axios.post("http://localhost:4000/todos", inputValue);
    fetchTodos();
  };

위에 데이터를 가져오는 함수인 fetchTodos를 다시한번 실행시키면 된다. 

그리고 인풋값을 비워주기 위해서 

  const addTodoHandler = async () => {
    axios.post("http://localhost:4000/todos", inputValue);
    fetchTodos();
    setInputValue({
      title: "",
    });
  };

inputValue 초기화 까지 해주면 완성 !

과정을 확인할 수 있는 영상이다!

 

delete와  patch(수정)이 남았는데 사실 방법은 유사 하기 때문에 간결하게 적고 가겠다.

  const [targetId, setTargetId] = useState("");
  const [editTitle, setEditTitle] = useState("");
  
const removeHandler = async (id) => {
    axios.delete(`http://localhost:4000/todos/${id}`);
    setTodos(
      todos.filter((todo) => {
        return todo.id !== id;
      })
    );
  };
  const editHandler = () => {
    axios.patch(`http://localhost:4000/todos/${targetId}`, {
      title: editTitle,
    });
    setTodos(
      todos.map((todo) => {
        if (todo.id == targetId) {
          return { ...todo, title: editTitle };
        } else {
          return todo;
        }
      })
    );
    setEditTitle("");
    setTargetId("");
  };

수정과 삭제는 둘다 해당하는 id에 맞는 글만 적용이 되어야하기 때문에 server url 뒤에 아이디를 특정할 수 있는 것을 넣어주어야한다. 

 

하지만 차이는  삭제는 인자로 onclick 이벤트시 받아오는 id를 받는 것이고 수정은 state를 받아오는 것이다. 고로 수정 로직에는 인자로 받아올 이유가 없다 .

'React' 카테고리의 다른 글

axios interceptor  (0) 2023.11.29
json server  (0) 2023.11.29
redux toolkit  (1) 2023.11.28
React router dom  (0) 2023.11.13
children 활용하기  (0) 2023.11.13