React.js (5) React async await

Bada Jung·2022년 1월 10일
0

React

목록 보기
5/11
post-thumbnail

async function await

ECMAScript2017 부터 추가되어,

API를 순차적으로 호출하기 위함

React Hook 와 사용 방법

  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchUsers = async () => {
    try {
      // 요청이 시작 할 때에는 error 와 users 를 초기화하고
      setError(null);
      setUser(null);
      // loading 상태를 true 로 바꿉니다.
      setLoading(true);
      const response = await axios.get("/api/user");
      setUser(response.data); // 데이터는 response.data 안에 들어있습니다.
      //console.log(response.data);
    } catch (e) {
      setError(e);
    }
    setLoading(false);
  };

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

  if (loading) return <div>로딩중..</div>;
  if (error) return <div>에러가 발생했습니다</div>;
  if (!user) return null;
profile
🌊🌊Under the SEA🌊🌊

0개의 댓글