TIL_36_221219

young0_0·2022년 12월 19일
0

TIL

목록 보기
35/91

36일 차 회고

  • axios error

axios error - 형변환

에러상황

  • todo의 기존 값을 가지고 오고, 내가 수정한 내용을 나타내야 하는 부분인데 map 아래 if(todo.id === todoId)아래로 콘솔을 찍으면 콘솔도 나타나지 않았다.
  • 근데 새로 고침을 하면 바뀜 ⇒ 애초에 새로고침 하지 않고 바뀌는 상황의 로직을 짜다가 발견된것
const onClickEditButtonHandler = (todoId, edit) => {
    axios.patch(`http://localhost:3001/todos/${todoId}`, edit);

    const newTodos = todos.map((todo) => {
      if (todo.id === todoId) {
        console.log('todo',  todo.id,  todoId); //아무값도 나오지 않음
        return { ...todo, title: edit.title };
      } else {
        return todo;
      }
    });
    console.log('newTodos', newTodos);
    console.log('todoId', todoId, edit.title);

    setTodos(newTodos);
  };

  useEffect(() => {
    fetchTodos();
  }, []);

에러해결

  • 새로고침 후 수정되는 이유 ⇒ db.json에서 처리되고 있었음.
  • todo.id(number) === todoId(string) 의 자료형이 서로 달라 수정된 값이 추가 되지 않았다.
  • 방법1 : 비교연산자를 ==로 변경 하면 변경이 되어서 자료형을 확인 해보니 다른것을 확인 하였다.
  • 해결 한 방법 : todoId의 값을 숫자로 형변환을 하고 비교연산자를 === 으로 변경하였다.
const onClickEditButtonHandler = (todoId, edit) => {
    axios.patch(`http://localhost:3001/todos/${todoId}`, edit);

    const newTodos = todos.map((todo) => {
      if (todo.id === +todoId) {
        console.log('todo', typeof todo.id, typeof +todoId); //아무값도 나오지 않음
        return { ...todo, title: edit.title };
      } else {
        return todo;
      }
    });
    console.log('newTodos', newTodos);
    console.log('todoId', todoId, edit.title);

    setTodos(newTodos);
  };

  useEffect(() => {
    fetchTodos();
  }, []);

에러해결 후 느낀점

2시간동안 고민하였는데 내가하는 방법에 대한 확신 없어서 좀더 고민하고 바로 튜텨님께 바로 가지 않아서
더 오래 걸린것 같다. 그래도 튜터님께 물어보니 속이 다 시원하다. 후..

profile
열심히 즐기자ㅏㅏㅏㅏㅏㅏㅏ😎

1개의 댓글

comment-user-thumbnail
2022년 12월 20일

매일 공부 안하는 척 하시면서,, 결국은 마스터 하셨군요. 축하드립니다.

답글 달기