1

At the very beginning of the app, it checks authorization from tokens in localStorage. So if a user closed and open a browser again, it checks authorization automatically if the token exists. But, because of that, if a user does the refresh in any places/pages of the app, it checks authorization again and shows the login page. I do want the auto-check from browser opening, but do not want auto-check from a refresh. How can I handle this?

useEffect(() => {
    dispatch(action.checkAuth());
  }, [dispatch]);

  return (
    <ConnectedRouter>
      <Switch>
        <Route exact path="/login" component={Login} />
        <RestrictedRoute
          path=""
          component={Main}
          isLoggedIn={idToken}
        />
      </Switch>
    </ConnectedRouter>
  );

Saga checkAuth function is here:

export function* checkAuth() {
  yield takeEvery(actions.CHECK_AUTH, function* ({ token }) {
      const userRes = yield call(
        fetch,
        apiPrefix + "/user?token=" + token
      );

      if (userRes === "200") {
        yield put({
          type: actions.LOGIN_SUCCESS,
          profile: userRes,
          isLoading: false,
        });

        yield put(push("/"));
      }
    } else {
      yield put({
        type: actions.LOGIN_ERROR,
        msg: "User does not exist.",
        isLoading: false,
      });
    }
  });
}
Sandy
  • 204
  • 1
  • 9

1 Answers1

2
useEffect(() => {
if(!localStorage.getItem("token")){
dispatch(action.checkAuth());
}}, [dispatch]);

Now this will work .