Search code examples
reactjsaxioses6-promise

React - user login and token validation


I've an AuthService component like this

class AuthService {

  // ... some code here

  private static isTokenValid = async (token: string | null) => {

    return await axios.post('https://example.net/wp-json/jwt-auth/v1/token/validate', null, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    }).then(res => {
      if (res.data.status === 200) return true;
    }).catch(e => {
      if (e.response.status === 403) return false;
    });
  }

  public static async isAuthorized() {
    const token = localStorage.getItem('token');

    let isValid;
    if (token) isValid = await this.isTokenValid(token);

    return token && isValid ? true : false;
  }
}

When I try to use it in React component, I got in isAuthorized Promise instead of boolean (true/false)

import AuthService from '../../services/auth/AuthService';
import React, { useEffect, useState } from 'react';

const NavBar = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  useEffect(() => {
    const isAuthorized = AuthService.isAuthorized();
    if (isAuthorized) setIsLoggedIn(isAuthorized);
  }, []);

  return (
     //...something...
  )
}

So what I'm doing wrong here?


Solution

  • The async function always returns a promise. See this.

    Try with this useEffect:

    useEffect(() => {
        AuthService
            .isAuthorized()
            .then((isAuthorized) => setIsLoggedIn(isAuthorized))
            .catch(() => setIsLoggedIn(false));
    }, []);