import React, { useCallback } from "react"; import { AppDispatch } from "app/store"; import { decodeToken } from "common/decodeToken"; import { useInterval } from "common/useInterval"; import { updateTokenAsync } from "features/auth/operations"; import { loadAccessToken } from "features/auth/utils"; import { DateTime } from "luxon"; import { useDispatch } from "react-redux"; //アクセストークンを更新する基準の秒数 const TOKEN_UPDATE_TIME = 5 * 60; //アクセストークンの更新チェックを行う間隔(ミリ秒) const TOKEN_UPDATE_INTERVAL_MS = 3 * 60 * 1000; export const UpdateTokenTimer = () => { const dispatch: AppDispatch = useDispatch(); // 期限が5分以内であれば更新APIを呼ぶ const updateToken = useCallback(async () => { // localStorageからトークンを取得 const jwt = loadAccessToken(); // selectorに以下の判定処理を移したかったが、初期表示時の値でしか判定できないのでComponent内に置く if (jwt) { const token = decodeToken(jwt); if (token) { const { exp } = token; const now = DateTime.local().toSeconds(); if (exp - now <= TOKEN_UPDATE_TIME) { await dispatch(updateTokenAsync()); } } } }, [dispatch]); useInterval(updateToken, TOKEN_UPDATE_INTERVAL_MS); // eslint-disable-next-line react/jsx-no-useless-fragment return <>; };