Home > Mobile >  Argument of type '' is not assignable - TypeScript problem
Argument of type '' is not assignable - TypeScript problem

Time:06-22

i've got a little problem with TypeScript. I'm trying to hold login token from firebase to prevent logout on site refresh, but i'm facing this problem:

  TS2345: Argument of type 'SetStateAction<string | null>' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.
    31 |   const loginHandler = (token: React.SetStateAction<string | null>) => {
    32 |     setToken(token);
  > 33 |     localStorage.setItem('token', token);
       |                                   ^^^^^
    34 |   };
    35 |
    36 |   const logoutHandler = () => {

Here's my code:

    const initialToken = localStorage.getItem('token');
    const [token, setToken] = useState(initialToken);

    const loginHandler = (token: React.SetStateAction<string | null>) => {
    setToken(token);
    localStorage.setItem('token', token);
    };

And link to my github repo with all code: https://github.com/xflameyoke/fake-store-app/blob/dev/src/store/context.tsx

CodePudding user response:

  const initialToken = localStorage.getItem('token')
  // force token to typed as string
  const [token, setToken] = useState(initialToken as string)

  // set token parameter to string
  const loginHandler = (token: string) => {
    setToken(token)
    localStorage.setItem('token', token)
  }

CodePudding user response:

Put your token in localStorage is a bad idea for security reasons...

Firebase Authentication does automatically (try to) restore the user's sign-in session when the page is reloaded, your code just isn't aware of it. To detect auth state changes, use an auth state listener (as shown in the documentation):

Refresh page get log out automatically in angular 5

firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
  // No user is signed in.
}
});
  • Related