React useAsync 훅

Beginner

This tutorial is from open-source community. Access the source code

소개

이 랩에서는 React 에서 비동기 호출을 처리하기 위해 useAsync 훅을 사용하는 방법을 배웁니다. 이 사용자 정의 훅을 사용하면 핸들러 함수를 정의한 다음 useReducer 훅을 사용하여 컴포넌트의 상태를 업데이트하면서 비동기적으로 실행할 수 있습니다. 이 랩을 마치면 React 애플리케이션에서 비동기 데이터를 처리하기 위한 재사용 가능한 코드를 만들 수 있습니다.

React useAsync 훅

index.htmlscript.js는 이미 VM 에 제공되었습니다. 일반적으로 script.jsstyle.css에만 코드를 추가하면 됩니다.

이 코드는 비동기 호출을 처리하는 사용자 정의 훅을 생성합니다. 핸들러 함수 fn을 인수로 받아들이고 state (value, error, 및 loading) 의 속성과 비동기 run 함수를 포함하는 객체를 반환합니다. run 함수는 제공된 콜백 fn을 실행하는 동시에 dispatch를 사용하여 필요에 따라 state를 업데이트합니다.

const useAsync = (fn) => {
  const initialState = { loading: false, error: null, value: null };

  const stateReducer = (state, action) => {
    switch (action.type) {
      case "start":
        return { loading: true, error: null, value: null };
      case "finish":
        return { loading: false, error: null, value: action.value };
      case "error":
        return { loading: false, error: action.error, value: null };
      default:
        return state;
    }
  };

  const [state, dispatch] = React.useReducer(stateReducer, initialState);

  const run = async (args = null) => {
    try {
      dispatch({ type: "start" });
      const value = await fn(args);
      dispatch({ type: "finish", value });
    } catch (error) {
      dispatch({ type: "error", error });
    }
  };

  return { ...state, run };
};

const RandomImage = (props) => {
  const imgFetch = useAsync((url) =>
    fetch(url).then((response) => response.json())
  );

  return (
    <div>
      <button
        onClick={() => imgFetch.run("https://dog.ceo/api/breeds/image/random")}
        disabled={imgFetch.loading}
      >
        Load image
      </button>
      <br />
      {imgFetch.loading && <div>Loading...</div>}
      {imgFetch.error && <div>Error {imgFetch.error}</div>}
      {imgFetch.value && (
        <img
          src={imgFetch.value.message}
          alt="avatar"
          width={400}
          height="auto"
        />
      )}
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<RandomImage />);

오른쪽 하단의 'Go Live'를 클릭하여 포트 8080 에서 웹 서비스를 실행하십시오. 그런 다음 Web 8080 탭을 새로 고쳐 웹 페이지를 미리 볼 수 있습니다.

요약

축하합니다! React useAsync Hook 랩을 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 기술을 향상시킬 수 있습니다.