본문 바로가기
스파르타코딩클럽/내일배움캠프

[TIL] 내일배움캠프 React 과정 2023.01.08

by heereal 2023. 1. 8.

Today I Learned

  • 팀 프로젝트 진행

 


new Date()로 날짜 출력하기

댓글을 작성할 때 date: new Date()를 이용해서 작성 날짜를 저장하고 date를 이용해서 댓글을 최신순으로 정렬할 수 있었다. 근데 댓글을 작성한 날짜를 화면에 보여줄 때 new Date()로 생성한 날짜를 그대로 가져오면 에러가 발생한다.

 

Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}). If you meant to render a collection of children, use an array instead.

 

firestore에서 확인해봤더니 new Date()로 생성한 데이터는 문자열 형태가 아니라 타임스탬프라는 형태로 이루어져 있는 거 같다. 그래서 date 정보를 slice로 잘라서 화면에 보여주려던 원래 계획은 실패했다.

 

const date = comment.date
const year = date.getFullYear();
const month = ("0" + (date.getMonth() + 1)).slice(-2);
const day = ("0" + date.getDate()).slice(-2);

이 방법도 시도해 봤는데 실패했다...

 

useQuery로 데이터 불러오기

저녁 내내 거의 useQuery를 연구하고 있다. 현재 문제점은 useQuery가 실행되기는 하는데 data에 계속 undefined가 들어간다는 것. 근데 이것저것 시도해보니 useQuery가 어떤 구조로 작동하는지는 알겠다.

 

const { data } = useQuery("communityComments", getComments)

일단 useQuery에는 쿼리 키와 함수를 담아야 한다. 나는 getComments라는 함수를 쿼리 함수로 설정했는데 이 함수가 return하는 값이 data에 들어간다.

 

const getComments = () => {
  const q = query(
    collection(dbService, "communityComments"),
    orderBy("date", "desc")
  );

  onSnapshot(q, (snapshot) => {
    const newComments = snapshot.docs.map((doc) => ({
      id: doc.id,
      ...doc.data()
    }))
    setComments(newComments)
  })
  return comments;
};

getComments는 firestore onSnapshot을 이용해서 데이터를 불러오는데 사실 firebase와 상관없이 return하는 값만 조작(?)해서 useQuery의 data에 담을 수 있다.

 

const [comments, setComments] = useState(["hello"]);

만약에 comments의 초기값을 ["hello"]로 설정해놓고 getComments가 comments를 return하도록 하면 data를 콘솔로 찍어봤을 때 Array ["hello"]가 그대로 들어간다.

그렇다면 getComments가 firesotre에서 불러온 데이터를 담은 배열을 return하도록 해주면 될 거 같다! 


회고

사실 오늘은 별 거 안 하고 다른 조 진행 상황을 좀 구경했다. 다른 조들도 멋진 결과물을 만들고 있는 거 같아서 발표날이 기대된다. 오늘의 가장 큰 성과는 mbti에 따라 버튼 컬러 바뀌는 것 구현한 거! useQuery도 계속 시도해보고 있지만 쉽지가 않다.

헤더랑 탭 바에도 배경색을 넣어봤다🥰

 

댓글