yamoo9 / likelion-FEQA

질문/답변 — 프론트엔드 스쿨, 멋사
29 stars 9 forks source link

[LAB-7] 작성글 등록 후 그에 해당하는 상세페이지로 이동시키고 싶습니다. #239

Closed hayeonn2 closed 1 year ago

hayeonn2 commented 1 year ago

질문 작성자

김하연

문제 상황

현재 QuestionWrite.jsx 에서 작업중 입니다. useNavigate() 를 이용해서 작성글을 모두 작성 후 등록했을 때 -> 그에 해당하는 페이지로 넘어가게 하고 싶습니다. 지금은 그냥 해당 글 리스트를 보여주는 navigate("/question/"); 로 연결시켜놓은 상태입니다. POST 한 후 이 아이디 값을 받아와서 navigate(/question/${id값}); 으로 받아서 그 페이지로 넘기려고 했습니다.

스크린샷 2023-03-26 오후 6 50 27

파이어베이스 데이터를 가져오는 방법 중 이 방법을 이용해서 해당 아이디 값을 추출하려고 했는데 잘 안되는 것 같습니다. (where가 잘 작동이 안되는 것 같습니다....)

스크린샷 2023-03-26 오후 6 52 06

현재 상태는

if (confirm("게시글을 등록하시겠습니까?")) {
      console.log("🧟‍♀️", docRef._key.path.segments[1]);
      const result = await getData(docRef._key.path.segments[1]);
      console.log("result입니다. ", result);
      resetTitle();
      navigate(`/question/`);
    }

게시글을 등록했을 때 저 키값을 받아오는지 콘솔창에 찍어본 상태이고.. 하지만 getData 를 실행했을 때 값이 전달이 안되는 것 같습니다.

스크린샷 2023-03-26 오후 6 47 42

작성 후 해당글로 이동시키려는데 이 방법이 옳지 않은건지 의문이 듭니다. 아니면 다른 방법이 있을까요.. 임의로 id값을 생성 후 그 id와 연결시켜야하는지 고민입니다.

프로젝트 저장소 URL

https://github.com/Likelion-lucky7/DECO/tree/question-write-category%23109

해당 브랜치는 question-write-category#109 입니다!

yamoo9 commented 1 year ago

문제 해결

Firestore에 의해 자동 추가된 문서 ID와 비교할 때는 documentId를 사용해야 합니다.

쿼리에서 문서 ID별로 정렬하거나 필터링하는 데 사용할 수 있습니다. It can be used in queries to sort or filter by the document ID.

import {
  // ...
  documentId,
} from "firebase/firestore";

const getData = async (questionId) => {
  const q = await query(
    collection(dbService, "question"),
    where(documentId(), "==", questionId),
  );

  const querySnapshot = await getDocs(q);
  return querySnapshot.docs[0].id;
};
const onSubmit = async (e) => {
  // ...

  if (confirm("게시글을 등록하시겠습니까?")) {
    const result = await getData(docRef._key.path.segments[1]);
    console.log("result입니다. ", result);
    navigate(`/question/${result}`);
  }
};

코드를 수정하면 result 결과 값이 정상적으로 출력됩니다. 😃