detail page CRUD error

KoEunseo·2022년 11월 3일
0

fixErr

목록 보기
5/23

detail페이지 CRUD 구현을 모두 마쳤다!!!!
진짜 어떻게 해도 안되던게 알고보니 진짜 별거아닌거였고 하는ㅎ
여턴 별 에러를 다 만났는데 정리를 해볼까 한다.

READ(GET) CREATE(POST) DELETE(DELETE) UPDATE(PATCH)

url을 제대로 보내야함...

get을 제일먼저 했다.
진작에 문제없이 구현이 됐는데 어제 pull하고 갑자기 화면이 안나오는 문제가 발생했음.
더미 데이터가 수정되었던 것...!!
백엔드분들이 초기에 테이블명세서를 주셔서 그걸 기반으로 했었는데, 테이블명세서가 변경이 되었다.
실 데이터 기반으로 테스트해보면서 다른 프론트분이 새로운 테이블명세대로 형태를 바꿔두셨었던...
별일 아닌거같은데 엄청 고생했다... typo 문제는 정말...^^ 없을수가 없는듯

원래 answer를 detail > answerList 이런 구조로만 했었는데,
crud를 하려니까 컴포넌트를 분리해야할 필요성을 느끼게 됨.
그래서 answerItem파일을 하나 더 만들었는데, 이게 자꾸 무한로딩인지 무한렌더링인지를 하더라.
알고보니 answerItem 내에서 answerItem을 호출하고있었다....ㅠㅠㅠㅠ
answerList에서 복사해서 answerItem에 붙여넣기를 해서ㅎ... 오늘하루 거의 저거 하는데 씀.
answerList에서 호출하는데 answerItem 내에서 또 호출하니까 계속 무한대로 돌아간것....
난 그것도모르고 props 제대로 못넘긴 줄 알고 별별걸 다 해봤다.
fetch되어서 전달하는 데이터라서 데이터가 오지 않았는데 화면 렌더링이 먼저 된건가 해서...^^
삼항연산자도 써보고 useState도 써보고...

그리고 create를 어젠가 했던 것 같다.
이상하게도 한 question 당 하나의 answer만 등록이 가능했었는데(???)
오늘 테스트해보니 정상적으로 작동함.
대체 뭐가 문제였을까;;;
아 빼놓을수없는 문제가 있었는데!!
post를 했을때 페이로드는 제대로 나오는데 500에러가 뜸...
id가 undefined라고하는데 내가 필요한 id는 잘 나왔는디 먼소리?
제이슨서버에서 id를 자동으로 부여해주는데, 내가 담아서 보낸 id가 고유한 값이라고 인식을 못한 것 같다.
answer_id: answers.length++ 이딴식으로 줘서 그런가...(긁적)
결론적으로 id는 서버가 부여하니까 생략했다.

오늘 delete를 먼저 했는데,
자꾸 이상한 에러가 떠서 검색해보니 http가 아니라 https로 요청을 보내서 문제가 발생했던것.

그리고 update를 하는데 아니 스택오버플로우 들어가서 보니까
edit 고 별거아녀보이는 버튼같지도 않은 버튼 누르면 edit 페이지로 넘어감;;;;
페이지를 하나 더 만들어야한다고!? 헐... 하다가
그냥 나자신과 타협하여 edit 컴포넌트를 하나 만들어서 해결했닼ㅋㅋㅋㅋㅋㅋ
역시나 fetch하는 과정에서 문제가 발생했는데, 다 url 제대로 못써서 생긴 문제였음

데이터 형식

{
   "question": {
      "data": [
         {
            "questionId": 5,
            "questionStatus": "QUESTION_EXIST",
            "title": "string",
            "body": "string",
            "view": 0,
            "createdAt": "2022-11-02T20:12:47.809521",
            "updatedAt": "2022-11-02T20:12:47.719745"
         },
         {
            "questionId": 4,
            "questionStatus": "QUESTION_EXIST",
            "title": "test",
            "body": "qwdawdawdawdawd",
            "view": 0,
            "createdAt": "2022-11-02T15:23:23.614035",
            "updatedAt": "2022-11-02T15:23:23.523276"
         },
         {
            "questionId": 3,
            "questionStatus": "QUESTION_EXIST",
            "title": "string",
            "body": "string",
            "view": 0,
            "createdAt": "2022-11-02T15:02:40.439374",
            "updatedAt": "2022-11-02T15:02:40.381612"
         },
         {
            "questionId": 2,
            "questionStatus": "QUESTION_EXIST",
            "title": "string1",
            "body": "string2",
            "view": 0,
            "createdAt": "2022-11-02T14:18:35.093064",
            "updatedAt": "2022-11-02T14:18:35.076376"
         }
      ],
      "pageInfo": {
         "page": 1,
         "size": 10,
         "totalElements": 4,
         "totalPages": 1
      }
   },
   "answer": [
      {
         "answerId": 1,
         "questionId": 2,
         "userId": "냠냠",
         "body": "hello world!"
      },
      {
         "answerId": 2,
         "questionId": 2,
         "userId": "바쁘다",
         "body": "bye world!"
      }
   ]
}

CREATE(POST) : /answer

  const handleSubmit = (e) => {
    e.preventDefault();
    const data = {
      questionId: 2,
      body: answer,
    };
    const fetchData = async () => {
      try {
        const url = `http://localhost:3001/answer`;
        await axios.post(url, data);
        window.location.reload();
      } catch (err) {
        console.log('error', err);
      }
    };
    fetchData();
  };

READ(GET) : /answer?questionId=${questionId}

  useEffect(() => {
    const fetchData = async () => {
      const url = `http://localhost:3001/answer?questionId=${questionId}`;
      try {
        await axios.get(url).then((res) => {
          setAnswers(res.data);
        });
      } catch (err) {
        console.log('error', err);
      }
    };
    fetchData();
  }, [questionId]);

DELETE(DELETE) : /answer/${id}

  const handleDelete = () => {
    console.log(id, body);
    const url = `http://localhost:3001/answer/${id}`;
    const fetchData = async () => {
      try {
        await axios.delete(url).then(() => {
          console.log(id, body);
          window.location.reload();
        });
      } catch (err) {
        console.log('error', err);
      }
    };
    fetchData();
  };

UPDATE(PATCH) : /answer/${answerId}

  const handleEditBtn = () => {
    // const url = REACT_APP_ANSWER + ${answerId};
    const url = `http://localhost:3001/answer/${answerId}`;
    const data = {
      id: answerId,
      answerStatus: 'ANSWER_NOT_EXIST',
      body: editText,
    };
    const fetchData = async () => {
      try {
        await axios.patch(url, data).then((res) => {
          console.log(res);
          setIsEdit(false);
        });
      } catch (err) {
        console.log('error', err);
      }
    };
    fetchData();
  };
profile
주니어 플러터 개발자의 고군분투기

0개의 댓글