ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • async await , then catch (feat. tryCatch)
    axios 2023. 5. 11. 17:00

     

    openWeather api 를 이용해 데이터를 전송받는 일을 비동기로 처리한다.

    처음엔 try catch , then catch 가 뭔지 혼동스럽고 그냥 돌아가는데로 사용했는데 어떤 분덕에 확실히 이해하게 되었다.

     

    callback 지옥을 해결하기 위한 Promise 가 등장하고

    Promise then ...then ...then ...then 을 조금더 편리하게 쓰기 위한 

    async await 가 등장했다. 이 async await 와 함께 try Catch 구문을 사용하면 에러핸들링도 가능하다!

     

    일단 내가 작성했던 첫번째 코드를 보자

    import { useEffect, useState } from "react";
    import axios from "axios";
    
    const WeatherHook = (period, area) => {
      const [data, setData] = useState({});
      const [isLoading, setIsLoading] = useState(false);
      const [isError, setIsError] = useState(false);
    
      useEffect(() => {
        setIsLoading(true)
        setIsError(false)
        let url;
        if (period === "week")
          url = `https://api.openweathermap.org/data/2.5/forecast?q=${area}&appid=${
            import.meta.env.VITE_APP_WEATHER
          }&units=metric`;
        if (period === "day")
          url = `https://api.openweathermap.org/data/2.5/weather?q=${area}&appid=${
            import.meta.env.VITE_APP_WEATHER
          }&units=metric`;
    
        axios
          .get(url)
          .then((Response) => {
            setData(Response.data);
            setIsLoading(false);
          })
          .catch((Error) => {
            setIsError(true);
          });
      }, [period, area]);
    
      return { data, isLoading, isError };
    };
    
    export default WeatherHook;

     

    ☀️ 주목해야할 부분은 이부분이다. 비록 콜백지옥보다는 좋지만 then 이 길어질 우려가 있다.

    axios
          .get(url)
          .then((Response) => {
            setData(Response.data);
            setIsLoading(false);
          })
          .catch((Error) => {
            setIsError(true);
          });

     

    🌈 그래서 좀더 좋아진 코드를 보자!

    import { useCallback, useEffect, useState } from "react";
    import axios from "axios";
    
    const WeatherHook = (period, area) => {
      const [data, setData] = useState({});
      const [isLoading, setIsLoading] = useState(false);
      const [isError, setIsError] = useState(false);
    
      const getWeatherData = useCallback(async () => {
        setIsLoading(true);
        setIsError(false);
        let url;
        if (period === "week")
          url = `https://api.openweathermap.org/data/2.5/forecast?q=${area}&appid=${
            import.meta.env.VITE_APP_WEATHER
          }&units=metric`;
        if (period === "day")
          url = `https://api.openweathermap.org/data/2.5/weather?q=${area}&appid=${
            import.meta.env.VITE_APP_WEATHER
          }&units=metric`;
    
        try {
          const res = await axios.get(url);
          setData(res.data);
        } catch (err) {
          setIsError(true);
        }
    
        setIsLoading(false);
      });
    
      useEffect(() => {
        
        getWeatherData();
    
        return () => {};
      }, [period, area]);
    
      return { data, isLoading, isError };
    };
    
    export default WeatherHook;

     

    ☀️ 주목해야할 부분은 이부분이다.  try catch 로 에러처리를 하며 비동기로 res 에 결과값을 담는다!

    /** 함수 시작할때 async 를 꼭 주는거 잊지 말기!*/
    
    try {
          const res = await axios.get(url);
          setData(res.data);
        } catch (err) {
          setIsError(true);
        }

    훨씬 간결해졌다!

    댓글

Designed by Tistory.