-1

i'm trying to use React Context to manage authentication, but i can't see the value that return the context in PrivateRoute.js

App.js

  render() {
  return (
    <>
    <BrowserRouter>
    <Islogin>
      <Header/>
    <Banner/>
     <Switch>
      <PrivateRoute exact path="/index" component={Landing} />
     <PrivateRoute path="/upload" component={Upload} exact />
     <PublicRoute restricted={false} path="/unauth" component={Unauthorized} exact  />
    </Switch>
    </Islogin>
    </BrowserRouter>
  
    </>
  );
}
}
export default App;

the console log of isAuthenticated returns undefined

PrivateRoute.js

const PrivateRoute = ({component: Component, ...rest}) => {
    const isAuthenticated  = useContext(AuthContext)
    console.log(isAuthenticated)
    const [validCredentials, setValidCredentials] = React.useState(false)
    React.useEffect(() => {
        if (typeof isAuthenticated === 'boolean') {
            setValidCredentials(isAuthenticated)
        }
    }, [isAuthenticated])
    return (
        // Show the component only when the user is logged in
        // Otherwise, redirect the user to /signin page
        <Route {...rest} render={props => (
            validCredentials  ?
                <Component {...props} />
            : <Redirect to="/unauth" />
        )} />
    );
};

export default PrivateRoute;

IsLogin.js

The api call works and the console log shows true.


export default function Islogin({ children }) {
    var [auth, setAuth] = React.useState(false)
   React.useEffect(() =>{
        axios.post('/api/auth').then(response => {
            var res = response.data.result;
            console.log("try")
            console.log(res)
            setAuth(res)
        })
    },[])
    
        return (
            <AuthContext.Provider value={auth}>
                {children}
            </AuthContext.Provider>
        )
}
Enzo Zalazar
  • 13
  • 1
  • 5

1 Answers1

1

You may need to import it at the top of the file that you are using it in (PrivateRoute.js)

Try this:

import {useContext} from 'react'
DJ Burb
  • 2,149
  • 1
  • 26
  • 38