code execution is not going inside react function

Viewed 68

When i try to call auth.isauthenticated(), execution flow is not going inside componentDidMount() function. It skips all code inside of componentDidMount() and goes directly to isAuthenticated function. this is the complete flow of my code.

import { Redirect, Route } from "react-router";
import auth from "./auth";

const ProtectedRoute = ({component: Component, ...rest} ) => {
    return ( 
        <Route  {...rest} render={
            (props) =>{
                if(auth.isAuthenticated()){
                    return <Component {...props} />
                }
                else{
                    return <Redirect to='/login' />
                }
            }
        } />
     );
}
 
export default ProtectedRoute;

import axios from 'axios'
import React from 'react';
import {constants} from './script/constant';

class Auth extends React.Component{

    constructor(){
        super();
        this.state = { 
            authenticated: false
        };
    }
    componentDidMount(){
        axios.get(`https://jsonplaceholder.typicode.com/users`)
        .then(res => {
            const userData = res.data;
            if(userData === ""){
                this.setState({authenticated: false});
                console.log("falseapi");
            }
            else{
                this.setState({authenticated:true});  
                console.log("trueapi");
            }            
        })  
    };
    isAuthenticated(){
        return this.state.authenticated;
    }

}
export default new Auth();
0 Answers
Related