Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hook (fetchData) #8

Open
yjkwon07 opened this issue Oct 11, 2020 · 0 comments
Open

Hook (fetchData) #8

yjkwon07 opened this issue Oct 11, 2020 · 0 comments
Labels
Hook Hook에 대한 고찰

Comments

@yjkwon07
Copy link
Member

How to fetch data with React Hooks?

const useDataApi = (initialUrl, initialData) => {
  const [url, setUrl] = useState(initialUrl);
 
  const [state, dispatch] = useReducer(dataFetchReducer, {
    isLoading: false,
    isError: false,
    data: initialData,
  });
 
  useEffect(() => {
    let didCancel = false;
 
    const fetchData = async () => {
      dispatch({ type: 'FETCH_INIT' });
 
      try {
        const result = await axios(url);
 
        if (!didCancel) {
          dispatch({ type: 'FETCH_SUCCESS', payload: result.data });
        }
      } catch (error) {
        if (!didCancel) {
          dispatch({ type: 'FETCH_FAILURE' });
        }
      }
    };
 
    fetchData();
 
    return () => {
      didCancel = true;
    };
  }, [url]);
 
  return [state, setUrl];
};
  • loading -> fetchData load 할 때 상태 표시
  • error -> 에러가 생길때 대처
  • race -> didCancel로 레이싱으로 일관성을 유지
  • fetchData에서 사용되는 data로 useEffect의 함수를 변하는 의존관계가 아니므로 useReducer로 묶어서 처리
@yjkwon07 yjkwon07 added the Hook Hook에 대한 고찰 label Oct 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Hook Hook에 대한 고찰
Projects
None yet
Development

No branches or pull requests

1 participant