axios + useEffect

KoEunseo·2022년 11월 1일
0

파헤쳐보자

목록 보기
10/31

음 한 세시간 헤맸음

원래코드

  const getDetail = async () => {
    await axios
      .get(`http://localhost:3001/data?questions_id=${id}`)
      .then((res) => {
        console.log(res.data[0]); //여기서는 잘 나오는데
        return res.data[0];
      })
      .catch((err) => {
        console.log(err);
      });
  };
  useEffect(() => {
    const fetchData = async () => {
      const data = await getDetail();
      setQuestion(data);
      console.log(question); //여기서는 null
      console.log(data); //여기서는 언디파인드
    };
    fetchData();
  }, []);

getDetail에서 찍은 콘솔은 잘 나오는데
useEffect 내에서 찍은 콘솔은 안나옴... 후
왜 이건 안되는걸까....??
async await으로 떡칠을 했는데 대체 왜 안나오는것인지....(떡실신)

axios말고 fetch로 썼을때

https://designcode.io/react-hooks-handbook-fetch-data-from-an-api

  useEffect(() => {
    const url = `http://localhost:3001/data?questions_id=${id}`;
    const fetchData = async () => {
      try {
        const res = await fetch(url);
        const json = await res.json();
        setQuestion(json[0]);
        console.log(json);
      } catch (err) {
        console.log('error', err);
      }
    };
    fetchData();
  }, []);

결론

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

어제까지 합치면 더 헤매긴 했다.
리덕스를 쓰려고 하니까 오히려 시간이 더 걸렸음....ㅠㅠㅠㅠㅠ
일단 리덕스는 포기하고 바인딩부터 함...

profile
주니어 플러터 개발자의 고군분투기

0개의 댓글