2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

axios.createを使う時の注意点とその対応

Posted at

はじめに

ReactでHTTPクライアントとしてよく選択されるものにaxiosがあります。
今回はそのaxiosに備わる機能、Axios Instanceについての注意とその対策法について紹介したいと思います。

その前に、件のAxios Instanceはどういうものかを一応簡単に解説します。
例えば以下のような設定をした時。

const customAxiosInstance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {
      Authorization: `Bearer ${localStorage.getItem("token")}`,
  }
});

 このcustomAxiosInstanceインスタンスを使用することで、baseURLtimeoutheadersを指定した状態でHTTPリクエストを送ることができます。

await customAxiosInstance.get("/users");
// リクエストを送る時に以下と同等になる!
// const response = await axios.get("https://some-domain.com/api/users", {
//   timeout: 1000,
//   headers: {
//      Authorization: `Bearer *******token***********`,
//   },
// });

問題

問題となるのは、Axios Instanceでtokenなどを管理している時です。

例えばlocalStorageに保存しているtokenをAxios Instanceで使用している場合。
非ログインの状態でサイトにアクセスした時、

const customAxiosInstance = axios.create({
    baseURL: "https://some-domain.com/api/",
    headers: {
        Authorization: `Bearer null`,
    },
});

この時、非ログインなので当然tokenはnullになります。

ここまではいいのですが、ここでユーザーがログインをしたとします。
そうするとtokenが発行され、localStorageに保存されるわけですが...

このcustomAxiosInstanceは当然ですが更新されず、従ってtokenはnullのままです。
バックエンド等との通信もうまくいかないことになります。

また、この現象はおそらくウィンドウの再リロードでしか解決できず(間違っていたらすみません🙇🏻‍♂️)、
ログイン、ログアウト時にwindow.location.reload()を実行というような無理矢理な方法をとらなければいけません。

結論としては、ログイン、非ログインなどユーザーの状態によって変動する値をリクエストに含めたい場合、
axiosの別の機能、すなわちInterceptorsを使用しましょう。

解決方法

Interceptorsは、リクエストの前後に任意の操作を挟み込める機能です。
これを使用した場合、先ほどのcustomAxiosInstanceは以下のようになります。
※これはミニマムであり、型やLintエラーが出る場合がありますが適宜修正してください🙏

const customAxiosInstance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
});

const authRequestInterceptor = (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem("token");

    if (token !== null) {
        // tokenがnullでない時、headerにAuthorizationを追加
        config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
};

// リクエストの前に、authRequestInterceptorの処理をする宣言
coustomAxiosInstance.interceptors.request.use(authRequestInterceptor);

こうすることで、axios.createの恩恵を受けつつ、tokenなどの状態が変わるようなパラメーターも問題なくリクエストに含めることができるようになります。

おわりに

最後までお読みいただきありがとうございました!
修正や違う方法の提案等あれば是非是非コメントにお願いします😃

参考サイト

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?