mage 456
mage 456

Reputation: 55

React typescript app how to stop logouts in refresh?

I am working in a react app built with typescript which takes Django api for log in. I am storing the json web token in my local storage. But the app still logs out automatically when I refresh the page. Here is what I have done

Django urls.py

    path('login/', obtain_jwt_token),

This api is called in react logInContainer. I am saving the token in my local storage.

const logInContainer: React.FC = () => {
  const dispatch = useDispatch();
  const api = new Api();
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [errorText, setError] = React.useState('');

  const signIn = async () => {
    const res = await api.post('/login/', {
      username: username,
      password: password,
    });
    const json = JSON.stringify(res);
    localStorage.setItem("user-info", json);
    if (res) {
      dispatch(logInAction(res.token));
    } else {
      setError('login failed');
    }
  }

My logInAction

export const LogInAction = (token: string): AuthTypes => {
  return {
    type: AuthTypes.logIn,
    payload: {
      token: token,
    }
  };
};

My authTypes.ts

export const AuthTypes= {
  logIn: "SIGN_IN",
  logOut: "SIGN_OUT",
} as const;

So far, the login works fine. and the token is also stored in local storage. But whenever I refresh my page, the app log outs automatically. I need to solve this issue. Any help regarding this will be appreciated.

Here is how logout happens

  const logOut = async () => {
    
    dispatch(logOutAction())
  };

This is called by

<IconButton onClick={logOut}>
    <ExitToApp />
</IconButton>

here is logOutAction

export const logOutAction = (): AuthTypes => {
  return {
    type: ActionTypes.logOut,
  };
};

In my reducer ts

import { AuthState, AuthTypes } from "./types";
const initialState: AuthState = {
  token: '',
  isSignIn: false,
};

Which goes to authTypes

case ActionTypes.signIn:
      return Object.assign({}, state, action.payload, { isSignIn: true });

Upvotes: 1

Views: 289

Answers (1)

Ajith
Ajith

Reputation: 2666

Could you please try to change your reducer code as given below

import { AuthState, AuthTypes } from "./types";
const initialState: AuthState = {
  token    : localStorage.getItem('token')? localStorage.getItem('token') : '',
  isSignIn : localStorage.getItem('token')? true : false,
};

Upvotes: 2

Related Questions