axios get 통신

이재호·2024년 7월 14일

React

목록 보기
9/14

오늘은 axios get 통신에 대해서 정리를 하려고 한다.
get 통신도 post 통신과 비슷하게 흘러간다. 우선 기존에 진행했던 프로젝트 코드와 비교를 해보자

JBTI

  useEffect(() => {
    fetchJellyResult();
  }, []);

  const fetchJellyResult = async () => {
    try {
      const response = await axios.get("/jResult");
      setJellyResult(response.data);
    } catch (error) {
      console.error("Error fetching jelly result:", error);
    }
  };

PenpalPens

    useEffect(() => {
        const makeQustion = async () => {
            try {
                const response = await axios.get("/share");
                const questionData = response.data.question;
                setQuestion(questionData);
            } catch (error) {
                console.error("Error fetching question:", error);
            }
        };

        makeQustion();
    }, []);
    useEffect(() => {
        const loadShareDiary = async () => {
            try {
                const response = await axios.get(`/shareMy?sIdx=${sIdx}`)
                setShare(response.data);
                console.log("다이어리 정보 불러오기 성공", share)
            } catch (error) {
                console.log("다이어리 정보 불러오기 실패", error);
            }
        };

        loadShareDiary();
    }, [sIdx]);

Library

    useEffect(() => {
        const loadBookStatus = async () => {
            try {
                const response = await axios.get('/chartRentList');
                setRentCnt(response.data.rentCnt);
                setBookCnt(response.data.bookCnt);
                console.log("대여 현황 데이터 들어왔다");
            } catch (error) {
                console.log("대여 현황 데이터 안 들어왔다", error);
            }
        };
        loadBookStatus();
    }, []);

이번 get 통신에서는 크게 차이가 없는 것 같다.

추가적으로 이번에 도서관 프로젝트를 진행하면서 평소 여러 가지 비동기 코드를 봤었는데, 요즘은 크게 2가지로 나뉘는 것 같다.

  1. async/await
  2. Promise

위에 작성된 코드들은 async/await 방식이고
Promise 코드는 다음과 같다.

axios.get('/chartRentList')
    .then(function (response) {
        setRentCnt(response.data.rentCnt);
        setBookCnt(response.data.bookCnt);
        console.log("대여 현황 데이터 들어왔다");
    })
    .catch(function (error) {
        console.log("대여 현황 데이터 안 들어왔다");
    });

결과적으로 상황에 맞는 방식으로 비동기 코드를 작성하면 될 것 같다.

profile
프론트엔드 개발자를 꿈꾸고 있습니다. 감사합니다.

0개의 댓글