makes-trail / application-sample

アプリ開発準備
0 stars 0 forks source link

React - fetchのかわりにaxiosを使う #14

Closed kawabata2018 closed 3 years ago

kawabata2018 commented 3 years ago

背景

To do

完了条件

kawabata2018 commented 3 years ago

axiosでcleanup!

useEffect(() => {
  // do something
  const source = axios.CancelToken.source();

  // do something
  const res = await axios(url.toString(), {
    cancelToken: source.token
  });

  // do something

  return () => source.cancel("Component got unmounted");
}
kawabata2018 commented 3 years ago

axios.interceptorsを使ったエラーハンドリング

import axios, { AxiosResponse, AxiosError } from 'axios';

const http = axios.create();

const onSuccess = (response: AxiosResponse) => response;

const onError = (error: AxiosError) => {
  if (axios.isCancel(error)) {
    console.log("request cancelled!");
    return;
  }
  if (error.message === "Network Error") {
    window.location.href = "/503";
    return;
  }
  if (typeof error.response === "undefined") {
    alert("予期せぬエラーが発生したよ。ぴえん");
    return Promise.reject(error);
  }
  switch (error.response.status) {
    case 500:
      window.location.href = "/500";
      return;
    default:
      alert("予期せぬエラーが発生したよ。ぴえん");
      return Promise.reject(error);
  }
};

http.interceptors.response.use(onSuccess, onError);

export default http;
kawabata2018 commented 3 years ago

25 で完了しているのでclose