본문 바로가기
트러블슈팅

댓글창 데이터 가져오는 방식 업데이트하기

by 우주속공간 2024. 1. 22.

 

문제 발생


comment 데이터를 관리하는 state를 구별없이 getComments 하나로 설정하니까 트윗 상자 하단에 위치한 댓글 버튼을 누르면 모든 트윗게시물의 댓글창이 열리는 문제가 발생했다.

 

실제 코드


 

수정 전

const openComments = ({ id, number }: any) => {
    customAxios
      .post("/getComments", {
        tweet_id: id,
      })
      .then((response) => {
        data[number].is_opened = response.data.is_opened;
        setGetData([...data]);
        setGetComments(response.data.data);
      });
  };

 

comment 값들을 관리하는 state를 getComments 하나로 설정하니까 댓글창을 열때마다 모든 트윗 댓글창 데이터가 바뀜

 

 

수정 후

const openComments = ({ id, number }: any) => {
    customAxios
      .post("/getComments", {
        tweet_id: id,
      })
      .then((response) => {
        data[number].is_opened = response.data.is_opened;
        data[number].comment = response.data.data;
        setGetData([...data]);
      });
  };

 

data가져올때 각 트윗마다 comment=[]빈배열을 넘겨주는데 이걸 활용함.

⇒ 트윗을 열면 트윗 인덱스 값을 가져와서 해당 트윗 댓글 배열만 수정해서 다시 업데이트 시켜줌. 각 트윗 게시물 댓글 state 각각 따로 관리

 

<img
	className="w-4 h-4 "
	alt="#"
	src={"/assets/messenger.png"}
	onClick={(e: any) => {
		t.is_opened === true
 			? closeComments(i)
			: openComments({ id: e.target.id, number: i });
		}}
	id={t.tweet_id}
 />

트윗 게시물 하단 댓글 버튼을 클릭하면 is_opened가 false일때 트윗 게시물 인덱스번호가 같이 넘겨줌

'트러블슈팅' 카테고리의 다른 글

express.static 정적 파일 가져오기  (0) 2024.01.22