React js PrivateRoute show hide a dashboard Component based on JSON web token and fetch callShow or hide element in ReactCan you force a React component to rerender without calling setState?How to pass props/state through Link and Route - react.jsPassing an Instance of a Service Through a Route in Reacthow to hide component is react and show another component?Pass custom data to PrivateRoute component in Reactreact-redux-firebase login promise resolving before auth state is updated, causing render troublesShow/Hide route components in reactnav component losing props. React router mistake?Show/Hide Navigation Component for certain routes in react

Why can't an Airbus A330 dump fuel in an emergency?

What does どうかと思う mean?

Are there account age or level requirements for obtaining special research?

Is using a hyperlink to close a modal a poor design decision?

Who was president?

Is "The life is beautiful" incorrect or just very non-idiomatic?

Does travel insurance for short flight delays exist?

for loop not working in bash

Why did MS-DOS applications built using Turbo Pascal fail to start with a division by zero error on faster systems?

Science fiction short story where aliens contact a drunk about Earth's impending destruction

Average period of peer review process

Is the term "small" applied differently between piston engine planes and jet engine planes?

Would it be possible to have a GMO that produces chocolate?

Most practical knots for hitching a line to an object while keeping the bitter end as tight as possible, without sag?

Numbers Decrease while Letters Increase

What to say to a student who has failed?

What is this symbol: semicircles facing eachother

Using `With[...]` with a list specification as a variable

Avoiding racist tropes in fantasy

Mathematical uses of string theory

Justifying the use of directed energy weapons

Would this system work to purify water?

Did a flight controller ever answer Flight with a no-go?

Why do all fields in a QFT transform like *irreducible* representations of some group?



React js PrivateRoute show hide a dashboard Component based on JSON web token and fetch call


Show or hide element in ReactCan you force a React component to rerender without calling setState?How to pass props/state through Link and Route - react.jsPassing an Instance of a Service Through a Route in Reacthow to hide component is react and show another component?Pass custom data to PrivateRoute component in Reactreact-redux-firebase login promise resolving before auth state is updated, causing render troublesShow/Hide route components in reactnav component losing props. React router mistake?Show/Hide Navigation Component for certain routes in react






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I need help when a user go to the URL http://localhost:3000/dashboard
if the admin already logged in before he will be able to see the Dashboard we just verify the token in his local-storage? i verify that JSON web token by sending it to the node.js app verify it if its good we send 200 status and if its bad token we send 401 status and based on the status we set the Private Route to show true or false, the fetch function its ready but i cant find a way to integrate it



this is the app files structure



my-app/
README.md
node_modules/
package.json
public/
index.html
favicon.ico
src/
|components/
|Clien/
|Home.js
|Home.css
|Header.js
|Footer.js
|admin/
|Auth.js
|PrivateRoute.js
|Admin.js
|Dashboard.js
|Dashboard.css
App.css
App.js
index.css
index.js
logo.svg


this is the function I use to check for JWT in local storage and verify the token sending it to the server get back the res and based on the response I wanna show the dashboard or redirect to Admin login form



right now everything works fine but only if I change the isAuthenticated (in Auth Class) manually I can't find a way to do the verification based on the fetch answer from the server,
I'm not sure if I should use the function in the Auth class as a function or should I create a Component with a state and componentDidMount()



please guide me as I'm a beginner:



this is the function



componentDidMount()
//get token from local storage if there is one
const jwttoken = localStorage.getItem('jwttoken');
const bearer = 'Bearer '+ jwttoken;
const data = new FormData();
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/verify`,
method: 'POST',
headers:
'Accept': 'application/json',
'Authorization': bearer,
,
body: data
).then( (res)=>
if (res.status === 401)
res.json()
.then( (res)=>
this.setState(
isLogedout: true,
)
localStorage.removeItem('jwttoken');
)
else if (res.status === 200)
res.json()
.then((res)=>
this.setState(
isLogedout: false,
adminEmail: res.adminEmail
)
this.props.history.push("/dashboard");

)
else
this.setState(
isLogedout: true,
)
localStorage.removeItem('jwttoken');

).catch((err) =>
// console.log(err)
)




this is the App Component where all routes are



import React, Component from "react";
import Route, from "react-router-dom";
// import Auth from "./Components/Admin/Auth"


import logo from "./Components/img/logo.jpg";
import headerimg from "./Components/img/header.png";
import "./App.css";
import Home from "./Components/Home";
import Dashboard from "./Components/Admin/Dashboard";
import Articles from "./Components/Articles";
import ArticleId from "./Components/ArticleId";
import Admin from "./Components/Admin/Admin.js";
import PrivateRoute from "./Components/Admin/PrivateRoute.js";


class App extends Component
constructor(props, context)
super(props, context);
this.state =
webiste:
title: "Website title",
headerimg: headerimg,
altheaderimg: "website header image",
logo: logo,
logotitle: "website logo "
,

;



render()
return (
<div className="app-container">
<Route exact path='/' render=(props) => <Home ...props setTab="home" /> />
<Route exact path='/home' render=(props) => <Home ...props setTab="home" /> />
<Route path='/articles' render=(props) => <Articles ...props setArticle="false" /> />
<Route path='/article/:id' render=(props) => <ArticleId ...props.match.params setArticle="false" /> />

<Route exact path='/services' render=(props) => <Home ...props setTab="services" /> />
<Route exact path='/events' render=(props) => <Home ...props setTab="events" /> />
<Route exact path='/about' render=(props) => <Home ...props setTab="about" /> />
<Route exact path='/contact' render=(props) => <Home ...props setTab="contact" /> />

<Route exact path='/admin' component=Admin />
<PrivateRoute exact path="/dashboard" component=Dashboard />

</div>

);



export default App;


this is the:
PrivateRoute Component



import React, Component from "react";
import Route, Redirect, from "react-router-dom";
import Auth from "./Auth"


export const PrivateRoute = ( component: Component, ...rest ) =>
return (
<Route ...rest render=(props) => (
Auth.isAuthenticated() === true
? <Component ...props />
: <Redirect to='/admin' />
) />
)



this is the:
Auth class



class Auth 

constructor()
this.authenticated = true;


login(cb)
this.authenticated = true;
cb();


logout(cb)
this.authenticated = false;
cb();


isAuthenticated()
return this.authenticated;




export default new Auth();


this is the:
Dashboard Component sorry its huge so I'm not including everything what it matters for me how to show and hide it in the PrivateRouter



class Dashboard extends Component 
constructor(props)
super(props);
this.state =
Articles: true,
AddArticles: false,
Messages: false,
Services: false,
Events: false,
About: false,
AdminContact: false,
AdminAddEvent: false,
WebsiteInfo: false,

isLogedin: '',

//dynamic className
classArticles: "admin-side-bar-button-selected",
classAddArticle: "admin-side-bar-button",
classEvents: "admin-side-bar-button",
classAddEvents: "admin-side-bar-button",
classServices: "admin-side-bar-button",
classAbout: "admin-side-bar-button",
classContact: "admin-side-bar-button",
classWebsiteInfo: "admin-side-bar-button",

;


render()
return (
<div>
< div key="1" className="all-dashboard-container" >

<div className="header-dashboard">
<AdminHeader logout=this.logout />
</div>

<div className="dashboard-container">
<div className="side-dashboard">
<button className=this.state.classArticles onClick=this.showArticles>Articles</button>
<div className="hr"></div>
<button className=this.state.classAddArticle onClick=this.showAddArticles>Add Aricle</button>
<div className="hr"></div>
<button className=this.state.classEvents onClick=this.showEvents>Events </button>
<div className="hr"></div>
<button className=this.state.classAddEvents onClick=this.showAdminAddEvent>Add Events</button>
<div className="hr"></div>
<button className=this.state.classServices onClick=this.showServices>Services </button>
<div className="hr"></div>
<button className=this.state.classAbout onClick=this.showAbout>About </button>
<div className="hr"></div>
<button className=this.state.classContact onClick=this.showContact>Contact</button>
<div className="hr"></div>
<button className=this.state.classWebsiteInfo onClick=this.showWebsiteInfo>Website Info </button>
<div className="hr"></div>
</div>

<div className="body-dashboard">
<div>
<div>
this.state.Articles && <div> <AdminPublishedArticles /> </div>
</div>

<div>
this.state.AddArticles && <div> <AdminAddArticle /> </div>
</div>

<div>
this.state.AdminAddEvent && <div> <AdminAddEvent /> </div>
</div>

<div>
this.state.Events && <div> <AdminPublishedEvents /> </div>
</div>

<div>
this.state.Services && <div> <AdminServices /> </div>
</div>

<div>
this.state.About && <div> <AdminAbout /> </div>
</div>

<div>
this.state.AdminContact && <div> <AdminContact/> </div>
</div>

<div>
this.state.WebsiteInfo && <div> <WebsiteInfo /> </div>
</div>

</div>

</div>
</div>

<div> <Footer/></div>

</div>
</div>
);



export default Dashboard;


this is the Admin Component its a login form



import React, Component from 'react';
import "./css/Admin.css";
import Auth from './Auth';
class Admin extends Component
constructor(props)
super(props);
this.state =
adminEmail: '',
password: '',
loginError: false,
isLogedout: null




componentDidMount()
//get token from local storage if there is one
const jwttoken = localStorage.getItem('jwttoken');
const bearer = 'Bearer '+ jwttoken;
const data = new FormData();
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/verify`,
method: 'POST',
headers:
'Accept': 'application/json',
'Authorization': bearer,
,
body: data
).then( (res)=>
if (res.status === 401)
res.json()
.then( (res)=>
this.setState(
isLogedout: true,
adminEmail: res.adminEmail
)
localStorage.removeItem('jwttoken');
)
else if (res.status === 200)
res.json()
.then((res)=>
this.setState(
isLogedout: false,
adminEmail: res.adminEmail
)
this.props.history.push("/dashboard");

)
else
this.setState(
isLogedout: true,
adminEmail: res.adminEmail
)
localStorage.removeItem('jwttoken');

).catch((err) =>
// console.log(err)
)



handleSubmit = (event) =>
event.preventDefault();
const data = new FormData();
data.append('email', this.state.email);
data.append('password', this.state.password);
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/login`,
method: 'POST',
headers:
'Accept': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded'
,
body: data
).then( (response)=>
if (response.status === 401)
response.json()
.then( (res)=>
console.log(res)
this.setState( loginError: true )
)
else if (response.status === 200)
response.json()
.then((res) => localStorage.setItem('jwttoken', res) )
.then((res)=>
Auth.login(()=>
this.props.history.push("/dashboard");
)

)

).catch((err) =>
err.json()
.then(console.log(err))
)


changeEventEmail = (event) =>
this.setState(
email: event.target.value,
loginError: false
);


changeEventPassword = (event) =>
this.setState(
password: event.target.value,
loginError: false
);



render()
return (
<div>
this.state.isLogedout &&
<div className="admin-login-container">

<form className="admin-login-form" onSubmit=this.handleSubmit>
<label>Email</label>
<input type="text" onChange=this.changeEventEmail value=this.state.email required />
<label >Password </label>
<input type="text" onChange=this.changeEventPassword value=this.state.password required />
<input className="admin-login-submit" type="submit" value="Login" />
</form>
this.state.loginError &&
<div className="admin-login-err">wrong email or password</div>

</div>
</div>
);



export default Admin;









share|improve this question





















  • 1





    It will be really nice if you can put a working code on jsfiddle or any other online editor. This will really help all of us. Thanks -KN

    – Kumar Nitesh
    Mar 27 at 16:52











  • or codesandbox.io

    – Jacob
    Mar 27 at 17:07











  • its a huge file a small CMS App with a connection to MySQL database in a Node.js server, so it will not work in jsfiddle or codesandbox.io , but i can create a copy of it without a MySQL database

    – DzHistory
    Mar 27 at 17:25

















0















I need help when a user go to the URL http://localhost:3000/dashboard
if the admin already logged in before he will be able to see the Dashboard we just verify the token in his local-storage? i verify that JSON web token by sending it to the node.js app verify it if its good we send 200 status and if its bad token we send 401 status and based on the status we set the Private Route to show true or false, the fetch function its ready but i cant find a way to integrate it



this is the app files structure



my-app/
README.md
node_modules/
package.json
public/
index.html
favicon.ico
src/
|components/
|Clien/
|Home.js
|Home.css
|Header.js
|Footer.js
|admin/
|Auth.js
|PrivateRoute.js
|Admin.js
|Dashboard.js
|Dashboard.css
App.css
App.js
index.css
index.js
logo.svg


this is the function I use to check for JWT in local storage and verify the token sending it to the server get back the res and based on the response I wanna show the dashboard or redirect to Admin login form



right now everything works fine but only if I change the isAuthenticated (in Auth Class) manually I can't find a way to do the verification based on the fetch answer from the server,
I'm not sure if I should use the function in the Auth class as a function or should I create a Component with a state and componentDidMount()



please guide me as I'm a beginner:



this is the function



componentDidMount()
//get token from local storage if there is one
const jwttoken = localStorage.getItem('jwttoken');
const bearer = 'Bearer '+ jwttoken;
const data = new FormData();
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/verify`,
method: 'POST',
headers:
'Accept': 'application/json',
'Authorization': bearer,
,
body: data
).then( (res)=>
if (res.status === 401)
res.json()
.then( (res)=>
this.setState(
isLogedout: true,
)
localStorage.removeItem('jwttoken');
)
else if (res.status === 200)
res.json()
.then((res)=>
this.setState(
isLogedout: false,
adminEmail: res.adminEmail
)
this.props.history.push("/dashboard");

)
else
this.setState(
isLogedout: true,
)
localStorage.removeItem('jwttoken');

).catch((err) =>
// console.log(err)
)




this is the App Component where all routes are



import React, Component from "react";
import Route, from "react-router-dom";
// import Auth from "./Components/Admin/Auth"


import logo from "./Components/img/logo.jpg";
import headerimg from "./Components/img/header.png";
import "./App.css";
import Home from "./Components/Home";
import Dashboard from "./Components/Admin/Dashboard";
import Articles from "./Components/Articles";
import ArticleId from "./Components/ArticleId";
import Admin from "./Components/Admin/Admin.js";
import PrivateRoute from "./Components/Admin/PrivateRoute.js";


class App extends Component
constructor(props, context)
super(props, context);
this.state =
webiste:
title: "Website title",
headerimg: headerimg,
altheaderimg: "website header image",
logo: logo,
logotitle: "website logo "
,

;



render()
return (
<div className="app-container">
<Route exact path='/' render=(props) => <Home ...props setTab="home" /> />
<Route exact path='/home' render=(props) => <Home ...props setTab="home" /> />
<Route path='/articles' render=(props) => <Articles ...props setArticle="false" /> />
<Route path='/article/:id' render=(props) => <ArticleId ...props.match.params setArticle="false" /> />

<Route exact path='/services' render=(props) => <Home ...props setTab="services" /> />
<Route exact path='/events' render=(props) => <Home ...props setTab="events" /> />
<Route exact path='/about' render=(props) => <Home ...props setTab="about" /> />
<Route exact path='/contact' render=(props) => <Home ...props setTab="contact" /> />

<Route exact path='/admin' component=Admin />
<PrivateRoute exact path="/dashboard" component=Dashboard />

</div>

);



export default App;


this is the:
PrivateRoute Component



import React, Component from "react";
import Route, Redirect, from "react-router-dom";
import Auth from "./Auth"


export const PrivateRoute = ( component: Component, ...rest ) =>
return (
<Route ...rest render=(props) => (
Auth.isAuthenticated() === true
? <Component ...props />
: <Redirect to='/admin' />
) />
)



this is the:
Auth class



class Auth 

constructor()
this.authenticated = true;


login(cb)
this.authenticated = true;
cb();


logout(cb)
this.authenticated = false;
cb();


isAuthenticated()
return this.authenticated;




export default new Auth();


this is the:
Dashboard Component sorry its huge so I'm not including everything what it matters for me how to show and hide it in the PrivateRouter



class Dashboard extends Component 
constructor(props)
super(props);
this.state =
Articles: true,
AddArticles: false,
Messages: false,
Services: false,
Events: false,
About: false,
AdminContact: false,
AdminAddEvent: false,
WebsiteInfo: false,

isLogedin: '',

//dynamic className
classArticles: "admin-side-bar-button-selected",
classAddArticle: "admin-side-bar-button",
classEvents: "admin-side-bar-button",
classAddEvents: "admin-side-bar-button",
classServices: "admin-side-bar-button",
classAbout: "admin-side-bar-button",
classContact: "admin-side-bar-button",
classWebsiteInfo: "admin-side-bar-button",

;


render()
return (
<div>
< div key="1" className="all-dashboard-container" >

<div className="header-dashboard">
<AdminHeader logout=this.logout />
</div>

<div className="dashboard-container">
<div className="side-dashboard">
<button className=this.state.classArticles onClick=this.showArticles>Articles</button>
<div className="hr"></div>
<button className=this.state.classAddArticle onClick=this.showAddArticles>Add Aricle</button>
<div className="hr"></div>
<button className=this.state.classEvents onClick=this.showEvents>Events </button>
<div className="hr"></div>
<button className=this.state.classAddEvents onClick=this.showAdminAddEvent>Add Events</button>
<div className="hr"></div>
<button className=this.state.classServices onClick=this.showServices>Services </button>
<div className="hr"></div>
<button className=this.state.classAbout onClick=this.showAbout>About </button>
<div className="hr"></div>
<button className=this.state.classContact onClick=this.showContact>Contact</button>
<div className="hr"></div>
<button className=this.state.classWebsiteInfo onClick=this.showWebsiteInfo>Website Info </button>
<div className="hr"></div>
</div>

<div className="body-dashboard">
<div>
<div>
this.state.Articles && <div> <AdminPublishedArticles /> </div>
</div>

<div>
this.state.AddArticles && <div> <AdminAddArticle /> </div>
</div>

<div>
this.state.AdminAddEvent && <div> <AdminAddEvent /> </div>
</div>

<div>
this.state.Events && <div> <AdminPublishedEvents /> </div>
</div>

<div>
this.state.Services && <div> <AdminServices /> </div>
</div>

<div>
this.state.About && <div> <AdminAbout /> </div>
</div>

<div>
this.state.AdminContact && <div> <AdminContact/> </div>
</div>

<div>
this.state.WebsiteInfo && <div> <WebsiteInfo /> </div>
</div>

</div>

</div>
</div>

<div> <Footer/></div>

</div>
</div>
);



export default Dashboard;


this is the Admin Component its a login form



import React, Component from 'react';
import "./css/Admin.css";
import Auth from './Auth';
class Admin extends Component
constructor(props)
super(props);
this.state =
adminEmail: '',
password: '',
loginError: false,
isLogedout: null




componentDidMount()
//get token from local storage if there is one
const jwttoken = localStorage.getItem('jwttoken');
const bearer = 'Bearer '+ jwttoken;
const data = new FormData();
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/verify`,
method: 'POST',
headers:
'Accept': 'application/json',
'Authorization': bearer,
,
body: data
).then( (res)=>
if (res.status === 401)
res.json()
.then( (res)=>
this.setState(
isLogedout: true,
adminEmail: res.adminEmail
)
localStorage.removeItem('jwttoken');
)
else if (res.status === 200)
res.json()
.then((res)=>
this.setState(
isLogedout: false,
adminEmail: res.adminEmail
)
this.props.history.push("/dashboard");

)
else
this.setState(
isLogedout: true,
adminEmail: res.adminEmail
)
localStorage.removeItem('jwttoken');

).catch((err) =>
// console.log(err)
)



handleSubmit = (event) =>
event.preventDefault();
const data = new FormData();
data.append('email', this.state.email);
data.append('password', this.state.password);
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/login`,
method: 'POST',
headers:
'Accept': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded'
,
body: data
).then( (response)=>
if (response.status === 401)
response.json()
.then( (res)=>
console.log(res)
this.setState( loginError: true )
)
else if (response.status === 200)
response.json()
.then((res) => localStorage.setItem('jwttoken', res) )
.then((res)=>
Auth.login(()=>
this.props.history.push("/dashboard");
)

)

).catch((err) =>
err.json()
.then(console.log(err))
)


changeEventEmail = (event) =>
this.setState(
email: event.target.value,
loginError: false
);


changeEventPassword = (event) =>
this.setState(
password: event.target.value,
loginError: false
);



render()
return (
<div>
this.state.isLogedout &&
<div className="admin-login-container">

<form className="admin-login-form" onSubmit=this.handleSubmit>
<label>Email</label>
<input type="text" onChange=this.changeEventEmail value=this.state.email required />
<label >Password </label>
<input type="text" onChange=this.changeEventPassword value=this.state.password required />
<input className="admin-login-submit" type="submit" value="Login" />
</form>
this.state.loginError &&
<div className="admin-login-err">wrong email or password</div>

</div>
</div>
);



export default Admin;









share|improve this question





















  • 1





    It will be really nice if you can put a working code on jsfiddle or any other online editor. This will really help all of us. Thanks -KN

    – Kumar Nitesh
    Mar 27 at 16:52











  • or codesandbox.io

    – Jacob
    Mar 27 at 17:07











  • its a huge file a small CMS App with a connection to MySQL database in a Node.js server, so it will not work in jsfiddle or codesandbox.io , but i can create a copy of it without a MySQL database

    – DzHistory
    Mar 27 at 17:25













0












0








0








I need help when a user go to the URL http://localhost:3000/dashboard
if the admin already logged in before he will be able to see the Dashboard we just verify the token in his local-storage? i verify that JSON web token by sending it to the node.js app verify it if its good we send 200 status and if its bad token we send 401 status and based on the status we set the Private Route to show true or false, the fetch function its ready but i cant find a way to integrate it



this is the app files structure



my-app/
README.md
node_modules/
package.json
public/
index.html
favicon.ico
src/
|components/
|Clien/
|Home.js
|Home.css
|Header.js
|Footer.js
|admin/
|Auth.js
|PrivateRoute.js
|Admin.js
|Dashboard.js
|Dashboard.css
App.css
App.js
index.css
index.js
logo.svg


this is the function I use to check for JWT in local storage and verify the token sending it to the server get back the res and based on the response I wanna show the dashboard or redirect to Admin login form



right now everything works fine but only if I change the isAuthenticated (in Auth Class) manually I can't find a way to do the verification based on the fetch answer from the server,
I'm not sure if I should use the function in the Auth class as a function or should I create a Component with a state and componentDidMount()



please guide me as I'm a beginner:



this is the function



componentDidMount()
//get token from local storage if there is one
const jwttoken = localStorage.getItem('jwttoken');
const bearer = 'Bearer '+ jwttoken;
const data = new FormData();
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/verify`,
method: 'POST',
headers:
'Accept': 'application/json',
'Authorization': bearer,
,
body: data
).then( (res)=>
if (res.status === 401)
res.json()
.then( (res)=>
this.setState(
isLogedout: true,
)
localStorage.removeItem('jwttoken');
)
else if (res.status === 200)
res.json()
.then((res)=>
this.setState(
isLogedout: false,
adminEmail: res.adminEmail
)
this.props.history.push("/dashboard");

)
else
this.setState(
isLogedout: true,
)
localStorage.removeItem('jwttoken');

).catch((err) =>
// console.log(err)
)




this is the App Component where all routes are



import React, Component from "react";
import Route, from "react-router-dom";
// import Auth from "./Components/Admin/Auth"


import logo from "./Components/img/logo.jpg";
import headerimg from "./Components/img/header.png";
import "./App.css";
import Home from "./Components/Home";
import Dashboard from "./Components/Admin/Dashboard";
import Articles from "./Components/Articles";
import ArticleId from "./Components/ArticleId";
import Admin from "./Components/Admin/Admin.js";
import PrivateRoute from "./Components/Admin/PrivateRoute.js";


class App extends Component
constructor(props, context)
super(props, context);
this.state =
webiste:
title: "Website title",
headerimg: headerimg,
altheaderimg: "website header image",
logo: logo,
logotitle: "website logo "
,

;



render()
return (
<div className="app-container">
<Route exact path='/' render=(props) => <Home ...props setTab="home" /> />
<Route exact path='/home' render=(props) => <Home ...props setTab="home" /> />
<Route path='/articles' render=(props) => <Articles ...props setArticle="false" /> />
<Route path='/article/:id' render=(props) => <ArticleId ...props.match.params setArticle="false" /> />

<Route exact path='/services' render=(props) => <Home ...props setTab="services" /> />
<Route exact path='/events' render=(props) => <Home ...props setTab="events" /> />
<Route exact path='/about' render=(props) => <Home ...props setTab="about" /> />
<Route exact path='/contact' render=(props) => <Home ...props setTab="contact" /> />

<Route exact path='/admin' component=Admin />
<PrivateRoute exact path="/dashboard" component=Dashboard />

</div>

);



export default App;


this is the:
PrivateRoute Component



import React, Component from "react";
import Route, Redirect, from "react-router-dom";
import Auth from "./Auth"


export const PrivateRoute = ( component: Component, ...rest ) =>
return (
<Route ...rest render=(props) => (
Auth.isAuthenticated() === true
? <Component ...props />
: <Redirect to='/admin' />
) />
)



this is the:
Auth class



class Auth 

constructor()
this.authenticated = true;


login(cb)
this.authenticated = true;
cb();


logout(cb)
this.authenticated = false;
cb();


isAuthenticated()
return this.authenticated;




export default new Auth();


this is the:
Dashboard Component sorry its huge so I'm not including everything what it matters for me how to show and hide it in the PrivateRouter



class Dashboard extends Component 
constructor(props)
super(props);
this.state =
Articles: true,
AddArticles: false,
Messages: false,
Services: false,
Events: false,
About: false,
AdminContact: false,
AdminAddEvent: false,
WebsiteInfo: false,

isLogedin: '',

//dynamic className
classArticles: "admin-side-bar-button-selected",
classAddArticle: "admin-side-bar-button",
classEvents: "admin-side-bar-button",
classAddEvents: "admin-side-bar-button",
classServices: "admin-side-bar-button",
classAbout: "admin-side-bar-button",
classContact: "admin-side-bar-button",
classWebsiteInfo: "admin-side-bar-button",

;


render()
return (
<div>
< div key="1" className="all-dashboard-container" >

<div className="header-dashboard">
<AdminHeader logout=this.logout />
</div>

<div className="dashboard-container">
<div className="side-dashboard">
<button className=this.state.classArticles onClick=this.showArticles>Articles</button>
<div className="hr"></div>
<button className=this.state.classAddArticle onClick=this.showAddArticles>Add Aricle</button>
<div className="hr"></div>
<button className=this.state.classEvents onClick=this.showEvents>Events </button>
<div className="hr"></div>
<button className=this.state.classAddEvents onClick=this.showAdminAddEvent>Add Events</button>
<div className="hr"></div>
<button className=this.state.classServices onClick=this.showServices>Services </button>
<div className="hr"></div>
<button className=this.state.classAbout onClick=this.showAbout>About </button>
<div className="hr"></div>
<button className=this.state.classContact onClick=this.showContact>Contact</button>
<div className="hr"></div>
<button className=this.state.classWebsiteInfo onClick=this.showWebsiteInfo>Website Info </button>
<div className="hr"></div>
</div>

<div className="body-dashboard">
<div>
<div>
this.state.Articles && <div> <AdminPublishedArticles /> </div>
</div>

<div>
this.state.AddArticles && <div> <AdminAddArticle /> </div>
</div>

<div>
this.state.AdminAddEvent && <div> <AdminAddEvent /> </div>
</div>

<div>
this.state.Events && <div> <AdminPublishedEvents /> </div>
</div>

<div>
this.state.Services && <div> <AdminServices /> </div>
</div>

<div>
this.state.About && <div> <AdminAbout /> </div>
</div>

<div>
this.state.AdminContact && <div> <AdminContact/> </div>
</div>

<div>
this.state.WebsiteInfo && <div> <WebsiteInfo /> </div>
</div>

</div>

</div>
</div>

<div> <Footer/></div>

</div>
</div>
);



export default Dashboard;


this is the Admin Component its a login form



import React, Component from 'react';
import "./css/Admin.css";
import Auth from './Auth';
class Admin extends Component
constructor(props)
super(props);
this.state =
adminEmail: '',
password: '',
loginError: false,
isLogedout: null




componentDidMount()
//get token from local storage if there is one
const jwttoken = localStorage.getItem('jwttoken');
const bearer = 'Bearer '+ jwttoken;
const data = new FormData();
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/verify`,
method: 'POST',
headers:
'Accept': 'application/json',
'Authorization': bearer,
,
body: data
).then( (res)=>
if (res.status === 401)
res.json()
.then( (res)=>
this.setState(
isLogedout: true,
adminEmail: res.adminEmail
)
localStorage.removeItem('jwttoken');
)
else if (res.status === 200)
res.json()
.then((res)=>
this.setState(
isLogedout: false,
adminEmail: res.adminEmail
)
this.props.history.push("/dashboard");

)
else
this.setState(
isLogedout: true,
adminEmail: res.adminEmail
)
localStorage.removeItem('jwttoken');

).catch((err) =>
// console.log(err)
)



handleSubmit = (event) =>
event.preventDefault();
const data = new FormData();
data.append('email', this.state.email);
data.append('password', this.state.password);
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/login`,
method: 'POST',
headers:
'Accept': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded'
,
body: data
).then( (response)=>
if (response.status === 401)
response.json()
.then( (res)=>
console.log(res)
this.setState( loginError: true )
)
else if (response.status === 200)
response.json()
.then((res) => localStorage.setItem('jwttoken', res) )
.then((res)=>
Auth.login(()=>
this.props.history.push("/dashboard");
)

)

).catch((err) =>
err.json()
.then(console.log(err))
)


changeEventEmail = (event) =>
this.setState(
email: event.target.value,
loginError: false
);


changeEventPassword = (event) =>
this.setState(
password: event.target.value,
loginError: false
);



render()
return (
<div>
this.state.isLogedout &&
<div className="admin-login-container">

<form className="admin-login-form" onSubmit=this.handleSubmit>
<label>Email</label>
<input type="text" onChange=this.changeEventEmail value=this.state.email required />
<label >Password </label>
<input type="text" onChange=this.changeEventPassword value=this.state.password required />
<input className="admin-login-submit" type="submit" value="Login" />
</form>
this.state.loginError &&
<div className="admin-login-err">wrong email or password</div>

</div>
</div>
);



export default Admin;









share|improve this question
















I need help when a user go to the URL http://localhost:3000/dashboard
if the admin already logged in before he will be able to see the Dashboard we just verify the token in his local-storage? i verify that JSON web token by sending it to the node.js app verify it if its good we send 200 status and if its bad token we send 401 status and based on the status we set the Private Route to show true or false, the fetch function its ready but i cant find a way to integrate it



this is the app files structure



my-app/
README.md
node_modules/
package.json
public/
index.html
favicon.ico
src/
|components/
|Clien/
|Home.js
|Home.css
|Header.js
|Footer.js
|admin/
|Auth.js
|PrivateRoute.js
|Admin.js
|Dashboard.js
|Dashboard.css
App.css
App.js
index.css
index.js
logo.svg


this is the function I use to check for JWT in local storage and verify the token sending it to the server get back the res and based on the response I wanna show the dashboard or redirect to Admin login form



right now everything works fine but only if I change the isAuthenticated (in Auth Class) manually I can't find a way to do the verification based on the fetch answer from the server,
I'm not sure if I should use the function in the Auth class as a function or should I create a Component with a state and componentDidMount()



please guide me as I'm a beginner:



this is the function



componentDidMount()
//get token from local storage if there is one
const jwttoken = localStorage.getItem('jwttoken');
const bearer = 'Bearer '+ jwttoken;
const data = new FormData();
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/verify`,
method: 'POST',
headers:
'Accept': 'application/json',
'Authorization': bearer,
,
body: data
).then( (res)=>
if (res.status === 401)
res.json()
.then( (res)=>
this.setState(
isLogedout: true,
)
localStorage.removeItem('jwttoken');
)
else if (res.status === 200)
res.json()
.then((res)=>
this.setState(
isLogedout: false,
adminEmail: res.adminEmail
)
this.props.history.push("/dashboard");

)
else
this.setState(
isLogedout: true,
)
localStorage.removeItem('jwttoken');

).catch((err) =>
// console.log(err)
)




this is the App Component where all routes are



import React, Component from "react";
import Route, from "react-router-dom";
// import Auth from "./Components/Admin/Auth"


import logo from "./Components/img/logo.jpg";
import headerimg from "./Components/img/header.png";
import "./App.css";
import Home from "./Components/Home";
import Dashboard from "./Components/Admin/Dashboard";
import Articles from "./Components/Articles";
import ArticleId from "./Components/ArticleId";
import Admin from "./Components/Admin/Admin.js";
import PrivateRoute from "./Components/Admin/PrivateRoute.js";


class App extends Component
constructor(props, context)
super(props, context);
this.state =
webiste:
title: "Website title",
headerimg: headerimg,
altheaderimg: "website header image",
logo: logo,
logotitle: "website logo "
,

;



render()
return (
<div className="app-container">
<Route exact path='/' render=(props) => <Home ...props setTab="home" /> />
<Route exact path='/home' render=(props) => <Home ...props setTab="home" /> />
<Route path='/articles' render=(props) => <Articles ...props setArticle="false" /> />
<Route path='/article/:id' render=(props) => <ArticleId ...props.match.params setArticle="false" /> />

<Route exact path='/services' render=(props) => <Home ...props setTab="services" /> />
<Route exact path='/events' render=(props) => <Home ...props setTab="events" /> />
<Route exact path='/about' render=(props) => <Home ...props setTab="about" /> />
<Route exact path='/contact' render=(props) => <Home ...props setTab="contact" /> />

<Route exact path='/admin' component=Admin />
<PrivateRoute exact path="/dashboard" component=Dashboard />

</div>

);



export default App;


this is the:
PrivateRoute Component



import React, Component from "react";
import Route, Redirect, from "react-router-dom";
import Auth from "./Auth"


export const PrivateRoute = ( component: Component, ...rest ) =>
return (
<Route ...rest render=(props) => (
Auth.isAuthenticated() === true
? <Component ...props />
: <Redirect to='/admin' />
) />
)



this is the:
Auth class



class Auth 

constructor()
this.authenticated = true;


login(cb)
this.authenticated = true;
cb();


logout(cb)
this.authenticated = false;
cb();


isAuthenticated()
return this.authenticated;




export default new Auth();


this is the:
Dashboard Component sorry its huge so I'm not including everything what it matters for me how to show and hide it in the PrivateRouter



class Dashboard extends Component 
constructor(props)
super(props);
this.state =
Articles: true,
AddArticles: false,
Messages: false,
Services: false,
Events: false,
About: false,
AdminContact: false,
AdminAddEvent: false,
WebsiteInfo: false,

isLogedin: '',

//dynamic className
classArticles: "admin-side-bar-button-selected",
classAddArticle: "admin-side-bar-button",
classEvents: "admin-side-bar-button",
classAddEvents: "admin-side-bar-button",
classServices: "admin-side-bar-button",
classAbout: "admin-side-bar-button",
classContact: "admin-side-bar-button",
classWebsiteInfo: "admin-side-bar-button",

;


render()
return (
<div>
< div key="1" className="all-dashboard-container" >

<div className="header-dashboard">
<AdminHeader logout=this.logout />
</div>

<div className="dashboard-container">
<div className="side-dashboard">
<button className=this.state.classArticles onClick=this.showArticles>Articles</button>
<div className="hr"></div>
<button className=this.state.classAddArticle onClick=this.showAddArticles>Add Aricle</button>
<div className="hr"></div>
<button className=this.state.classEvents onClick=this.showEvents>Events </button>
<div className="hr"></div>
<button className=this.state.classAddEvents onClick=this.showAdminAddEvent>Add Events</button>
<div className="hr"></div>
<button className=this.state.classServices onClick=this.showServices>Services </button>
<div className="hr"></div>
<button className=this.state.classAbout onClick=this.showAbout>About </button>
<div className="hr"></div>
<button className=this.state.classContact onClick=this.showContact>Contact</button>
<div className="hr"></div>
<button className=this.state.classWebsiteInfo onClick=this.showWebsiteInfo>Website Info </button>
<div className="hr"></div>
</div>

<div className="body-dashboard">
<div>
<div>
this.state.Articles && <div> <AdminPublishedArticles /> </div>
</div>

<div>
this.state.AddArticles && <div> <AdminAddArticle /> </div>
</div>

<div>
this.state.AdminAddEvent && <div> <AdminAddEvent /> </div>
</div>

<div>
this.state.Events && <div> <AdminPublishedEvents /> </div>
</div>

<div>
this.state.Services && <div> <AdminServices /> </div>
</div>

<div>
this.state.About && <div> <AdminAbout /> </div>
</div>

<div>
this.state.AdminContact && <div> <AdminContact/> </div>
</div>

<div>
this.state.WebsiteInfo && <div> <WebsiteInfo /> </div>
</div>

</div>

</div>
</div>

<div> <Footer/></div>

</div>
</div>
);



export default Dashboard;


this is the Admin Component its a login form



import React, Component from 'react';
import "./css/Admin.css";
import Auth from './Auth';
class Admin extends Component
constructor(props)
super(props);
this.state =
adminEmail: '',
password: '',
loginError: false,
isLogedout: null




componentDidMount()
//get token from local storage if there is one
const jwttoken = localStorage.getItem('jwttoken');
const bearer = 'Bearer '+ jwttoken;
const data = new FormData();
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/verify`,
method: 'POST',
headers:
'Accept': 'application/json',
'Authorization': bearer,
,
body: data
).then( (res)=>
if (res.status === 401)
res.json()
.then( (res)=>
this.setState(
isLogedout: true,
adminEmail: res.adminEmail
)
localStorage.removeItem('jwttoken');
)
else if (res.status === 200)
res.json()
.then((res)=>
this.setState(
isLogedout: false,
adminEmail: res.adminEmail
)
this.props.history.push("/dashboard");

)
else
this.setState(
isLogedout: true,
adminEmail: res.adminEmail
)
localStorage.removeItem('jwttoken');

).catch((err) =>
// console.log(err)
)



handleSubmit = (event) =>
event.preventDefault();
const data = new FormData();
data.append('email', this.state.email);
data.append('password', this.state.password);
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/login`,
method: 'POST',
headers:
'Accept': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded'
,
body: data
).then( (response)=>
if (response.status === 401)
response.json()
.then( (res)=>
console.log(res)
this.setState( loginError: true )
)
else if (response.status === 200)
response.json()
.then((res) => localStorage.setItem('jwttoken', res) )
.then((res)=>
Auth.login(()=>
this.props.history.push("/dashboard");
)

)

).catch((err) =>
err.json()
.then(console.log(err))
)


changeEventEmail = (event) =>
this.setState(
email: event.target.value,
loginError: false
);


changeEventPassword = (event) =>
this.setState(
password: event.target.value,
loginError: false
);



render()
return (
<div>
this.state.isLogedout &&
<div className="admin-login-container">

<form className="admin-login-form" onSubmit=this.handleSubmit>
<label>Email</label>
<input type="text" onChange=this.changeEventEmail value=this.state.email required />
<label >Password </label>
<input type="text" onChange=this.changeEventPassword value=this.state.password required />
<input className="admin-login-submit" type="submit" value="Login" />
</form>
this.state.loginError &&
<div className="admin-login-err">wrong email or password</div>

</div>
</div>
);



export default Admin;






reactjs react-router






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 17:12









Jacob

3842 silver badges13 bronze badges




3842 silver badges13 bronze badges










asked Mar 27 at 16:42









DzHistory DzHistory

12 bronze badges




12 bronze badges










  • 1





    It will be really nice if you can put a working code on jsfiddle or any other online editor. This will really help all of us. Thanks -KN

    – Kumar Nitesh
    Mar 27 at 16:52











  • or codesandbox.io

    – Jacob
    Mar 27 at 17:07











  • its a huge file a small CMS App with a connection to MySQL database in a Node.js server, so it will not work in jsfiddle or codesandbox.io , but i can create a copy of it without a MySQL database

    – DzHistory
    Mar 27 at 17:25












  • 1





    It will be really nice if you can put a working code on jsfiddle or any other online editor. This will really help all of us. Thanks -KN

    – Kumar Nitesh
    Mar 27 at 16:52











  • or codesandbox.io

    – Jacob
    Mar 27 at 17:07











  • its a huge file a small CMS App with a connection to MySQL database in a Node.js server, so it will not work in jsfiddle or codesandbox.io , but i can create a copy of it without a MySQL database

    – DzHistory
    Mar 27 at 17:25







1




1





It will be really nice if you can put a working code on jsfiddle or any other online editor. This will really help all of us. Thanks -KN

– Kumar Nitesh
Mar 27 at 16:52





It will be really nice if you can put a working code on jsfiddle or any other online editor. This will really help all of us. Thanks -KN

– Kumar Nitesh
Mar 27 at 16:52













or codesandbox.io

– Jacob
Mar 27 at 17:07





or codesandbox.io

– Jacob
Mar 27 at 17:07













its a huge file a small CMS App with a connection to MySQL database in a Node.js server, so it will not work in jsfiddle or codesandbox.io , but i can create a copy of it without a MySQL database

– DzHistory
Mar 27 at 17:25





its a huge file a small CMS App with a connection to MySQL database in a Node.js server, so it will not work in jsfiddle or codesandbox.io , but i can create a copy of it without a MySQL database

– DzHistory
Mar 27 at 17:25












1 Answer
1






active

oldest

votes


















0















in the Auth.js Class change the isAuthanticated to:



isAuthenticated() 
//get token from local storage if there is one
const jwttoken = localStorage.getItem('jwttoken');
const bearer = 'Bearer ' + jwttoken;
const data = new FormData();
// get the website backend main url from .env
const REACT_APP_URL = process.env.REACT_APP_URL
fetch(`$REACT_APP_URL/api/auth/verify`,
method: 'POST',
headers:
'Accept': 'application/json',
'Authorization': bearer,
,
body: data
).then(
(response) =>
response.json()
.then((res) =>
if (response.status === 200)
this.authenticated = true;

if (response.status === 401)
localStorage.removeItem('jwttoken');
this.authenticated = false;

)

).catch((err) =>
console.log(err)
);
return this.authenticated;



in PrivateRoute make sure you call Auth.isAuthanticated()
so you get true or false based on the fetch call witch will set authenticated to true or false and it will return this.authenticated;
you are doing it the right way just check spelling



import React, Component from "react";
import Route, Redirect, from "react-router-dom";
import Auth from "./Auth"


export const PrivateRoute = ( component: Component, ...rest ) =>
return (
<Route ...rest render=(props) => (
Auth.isAuthenticated() === true
? <Component ...props />
: <Redirect to='/admin' />
) />
)






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55382418%2freact-js-privateroute-show-hide-a-dashboard-component-based-on-json-web-token-an%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0















    in the Auth.js Class change the isAuthanticated to:



    isAuthenticated() 
    //get token from local storage if there is one
    const jwttoken = localStorage.getItem('jwttoken');
    const bearer = 'Bearer ' + jwttoken;
    const data = new FormData();
    // get the website backend main url from .env
    const REACT_APP_URL = process.env.REACT_APP_URL
    fetch(`$REACT_APP_URL/api/auth/verify`,
    method: 'POST',
    headers:
    'Accept': 'application/json',
    'Authorization': bearer,
    ,
    body: data
    ).then(
    (response) =>
    response.json()
    .then((res) =>
    if (response.status === 200)
    this.authenticated = true;

    if (response.status === 401)
    localStorage.removeItem('jwttoken');
    this.authenticated = false;

    )

    ).catch((err) =>
    console.log(err)
    );
    return this.authenticated;



    in PrivateRoute make sure you call Auth.isAuthanticated()
    so you get true or false based on the fetch call witch will set authenticated to true or false and it will return this.authenticated;
    you are doing it the right way just check spelling



    import React, Component from "react";
    import Route, Redirect, from "react-router-dom";
    import Auth from "./Auth"


    export const PrivateRoute = ( component: Component, ...rest ) =>
    return (
    <Route ...rest render=(props) => (
    Auth.isAuthenticated() === true
    ? <Component ...props />
    : <Redirect to='/admin' />
    ) />
    )






    share|improve this answer





























      0















      in the Auth.js Class change the isAuthanticated to:



      isAuthenticated() 
      //get token from local storage if there is one
      const jwttoken = localStorage.getItem('jwttoken');
      const bearer = 'Bearer ' + jwttoken;
      const data = new FormData();
      // get the website backend main url from .env
      const REACT_APP_URL = process.env.REACT_APP_URL
      fetch(`$REACT_APP_URL/api/auth/verify`,
      method: 'POST',
      headers:
      'Accept': 'application/json',
      'Authorization': bearer,
      ,
      body: data
      ).then(
      (response) =>
      response.json()
      .then((res) =>
      if (response.status === 200)
      this.authenticated = true;

      if (response.status === 401)
      localStorage.removeItem('jwttoken');
      this.authenticated = false;

      )

      ).catch((err) =>
      console.log(err)
      );
      return this.authenticated;



      in PrivateRoute make sure you call Auth.isAuthanticated()
      so you get true or false based on the fetch call witch will set authenticated to true or false and it will return this.authenticated;
      you are doing it the right way just check spelling



      import React, Component from "react";
      import Route, Redirect, from "react-router-dom";
      import Auth from "./Auth"


      export const PrivateRoute = ( component: Component, ...rest ) =>
      return (
      <Route ...rest render=(props) => (
      Auth.isAuthenticated() === true
      ? <Component ...props />
      : <Redirect to='/admin' />
      ) />
      )






      share|improve this answer



























        0














        0










        0









        in the Auth.js Class change the isAuthanticated to:



        isAuthenticated() 
        //get token from local storage if there is one
        const jwttoken = localStorage.getItem('jwttoken');
        const bearer = 'Bearer ' + jwttoken;
        const data = new FormData();
        // get the website backend main url from .env
        const REACT_APP_URL = process.env.REACT_APP_URL
        fetch(`$REACT_APP_URL/api/auth/verify`,
        method: 'POST',
        headers:
        'Accept': 'application/json',
        'Authorization': bearer,
        ,
        body: data
        ).then(
        (response) =>
        response.json()
        .then((res) =>
        if (response.status === 200)
        this.authenticated = true;

        if (response.status === 401)
        localStorage.removeItem('jwttoken');
        this.authenticated = false;

        )

        ).catch((err) =>
        console.log(err)
        );
        return this.authenticated;



        in PrivateRoute make sure you call Auth.isAuthanticated()
        so you get true or false based on the fetch call witch will set authenticated to true or false and it will return this.authenticated;
        you are doing it the right way just check spelling



        import React, Component from "react";
        import Route, Redirect, from "react-router-dom";
        import Auth from "./Auth"


        export const PrivateRoute = ( component: Component, ...rest ) =>
        return (
        <Route ...rest render=(props) => (
        Auth.isAuthenticated() === true
        ? <Component ...props />
        : <Redirect to='/admin' />
        ) />
        )






        share|improve this answer













        in the Auth.js Class change the isAuthanticated to:



        isAuthenticated() 
        //get token from local storage if there is one
        const jwttoken = localStorage.getItem('jwttoken');
        const bearer = 'Bearer ' + jwttoken;
        const data = new FormData();
        // get the website backend main url from .env
        const REACT_APP_URL = process.env.REACT_APP_URL
        fetch(`$REACT_APP_URL/api/auth/verify`,
        method: 'POST',
        headers:
        'Accept': 'application/json',
        'Authorization': bearer,
        ,
        body: data
        ).then(
        (response) =>
        response.json()
        .then((res) =>
        if (response.status === 200)
        this.authenticated = true;

        if (response.status === 401)
        localStorage.removeItem('jwttoken');
        this.authenticated = false;

        )

        ).catch((err) =>
        console.log(err)
        );
        return this.authenticated;



        in PrivateRoute make sure you call Auth.isAuthanticated()
        so you get true or false based on the fetch call witch will set authenticated to true or false and it will return this.authenticated;
        you are doing it the right way just check spelling



        import React, Component from "react";
        import Route, Redirect, from "react-router-dom";
        import Auth from "./Auth"


        export const PrivateRoute = ( component: Component, ...rest ) =>
        return (
        <Route ...rest render=(props) => (
        Auth.isAuthenticated() === true
        ? <Component ...props />
        : <Redirect to='/admin' />
        ) />
        )







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 28 at 8:51









        RidaRida

        8559 silver badges17 bronze badges




        8559 silver badges17 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55382418%2freact-js-privateroute-show-hide-a-dashboard-component-based-on-json-web-token-an%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현