props 초기화 문제 : useEffect 사용

KoEunseo·2022년 11월 7일
0

fixErr

목록 보기
6/23
post-custom-banner

안된코드

import { useEffect, useState } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import AnswerEditor from './AnswerEditor';
import AnswerItem from './AnswerItem';

const AnswersWrapper = styled.div`
  padding: 24px 0;
`;

const AnswerList = ({ questionId }) => {
  const [answers, setAnswers] = useState([]);
  const [pageInfo, setPageInfo] = useState();
  const [selectedPage, setSelectedPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);

  //answer전체조회
  async function getAnswerList({ page, size }) {
    const res = await axios.get(
      `${process.env.REACT_APP_ANSWER}?page=${page}&size=${size}`
    );
    return res.data;
  }
  useEffect(() => {
    const fetchData = async () => {
      const data = await getAnswerList({
        page: selectedPage,
        size: pageSize,
      });

      setPageInfo(data.pageInfo);
      setAnswers(data.data);
    };

    fetchData();
  }, [selectedPage, pageSize]);
  console.log(answers);

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

  return (
    <AnswersWrapper>
      {answers
        ? answers.map((answer) => {
            return (
              <>
                <AnswerItem key={answer.answerId} answer={answer} />
              </>
            );
          })
        : null}
      <AnswerEditor questionId={questionId} />
    </AnswersWrapper>
  );
};

export default AnswerList;
const Detail = () => {
  let { id } = useParams();
  const [question, setQuestion] = useState(null);

  useEffect(() => {
    const url = `${process.env.REACT_APP_QUESTION}/${id}`;
    const fetchData = async () => {
      try {
        await axios.get(url).then((res) => {
          setQuestion(res.data);
        });
      } catch (err) {
        console.log('error', err);
      }
    };
    fetchData();
  }, [id]);
}
  const [pageInf, setPageInf] = useState();
  const url = `${process.env.REACT_APP_QUESTION}/${id}?page=${page}&size=${size}`;
  useEffect(() => {
    window.localStorage.setItem('pageInfo', JSON.stringify(pageInfo));
    const savedPageInfo = localStorage.getItem('pageInfo');
    if (savedPageInfo !== null) {
      setPageInf(JSON.parse(savedPageInfo));
    }
  }, [pageInfo]);

된코드

export const getSpecificQuestion = async ({ questionId, page, size }) => {
  const res = await axios.get(
    `${process.env.REACT_APP_QUESTION}/${questionId}?page=${page}&size=${size}`
  );

  return res.data;
};

분리하고

  let { id } = useParams();
  const [question, setQuestion] = useState(null);
  const [selectedPage, setSelectedPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  useEffect(() => {
    const fetchData = async () => {
      const data = await getSpecificQuestion({
        questionId: id,
        page: selectedPage,
        size: pageSize,
      });
      setPageInfo(data.pageInfo);
      setQuestion(data.data);
    };
    fetchData();
  }, [id, pageSize, selectedPage, setPageInfo]);
profile
주니어 플러터 개발자의 고군분투기
post-custom-banner

0개의 댓글