Hi am new to react and facing a problem in react router . Actually am using useNavigate in react router dom for navigation and everything is working fine but my problem is suppose initially i am on page one then using useNavigate in am reaching to page two then from page two to page 3. Now when am refreshing the page everything is getting started with page 1 again but, what i want is if am on page 3 then on refreshing must be on page 3 is there any way to achieve it.
for example i am using two pages (my goal is if i am on 2nd page on refresh i must be on 2nd page) but for current situation browser is starting from first page
i am writing my first page like this
import react from "react";
import "../../../../css/panel/articleverificationpanel/topmostTray.css";
import axios from "axios";
import { useNavigate } from 'react-router-dom'
class MainLoginAreaForPanel extends react.Component {
goButtonClicked =() => {
try {
const userId = document.getElementById("userId").value;
const password = document.getElementById("password").value;
const securityKey = document.getElementById("securityKey").value;
console.log(userId, password, securityKey);
const data = {
userId,
password,
securityKey,
};
axios
.post(
`http://localhost:4000/app/panel/articleverification/signin`,
data
)
.then((res) => {
// means file has been uploaded
if (res.data.success === 1) {
console.log(this.props)
this.props.authorizeUser(true,{})
this.props.navigation('/panel/articleverification/homepage',{replace:true})
} else {
throw new Error('Sorry could not verify you');
}
})
.catch((error) => {
alert(error.message);
});
} catch (error) {
alert(error.message);
}
}
render() {
return (
<react.Fragment>
<div id="mainLoginPanelArea">
<label htmlFor="userId" className="children">
User id:
</label>
{" "}
<input type="text" id="userId" name="userId" className="children" />
<br />
<br />
<label htmlFor="password">Password:</label>
{" "}
<input type="text" id="password" name="password" />
<br />
<br />
<label htmlFor="securityKey">Security Key:</label>
{" "}
<input type="text" id="securityKey" name="securityKey" />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<button className="btn" onClick={this.goButtonClicked}>
GO
</button>
</div>
</react.Fragment>
);
}
}
// Wrap and export
export default function(props) {
const navigation = useNavigate();
return <MainLoginAreaForPanel {...props} navigation={navigation} />;
}
this is how i am writing my second page
import react from "react";
import TopmostTrayForPanel from "./topmostTray";
import CardForPanel from "./cardForPanel";
import {Navigate,useNavigate} from 'react-router-dom'
import axios from "axios";
class HomePageForArticalVerificationPanel extends react.Component {
state = {
data: [],
};
openArticle = (articleId) => {
this.props.navigation('/panel/articleverification/articlepage',{replace:true,state:
{articleId:articleId}
})
}
componentDidMount() {
console.log("loaded");
this.getUnverifiedArticles();
}
getUnverifiedArticles() {
let data = [];
let cnt = 0;
let temp = [];
axios
.get(
`http://localhost:4000/app/panel/articleverification/getunverifiedarticles`,
data
)
.then((res) => {
console.log(res)
if (res.data.success === 1) {
const articles = res.data.data.articles
for (let i = 0; i < articles.length; i ) {
if (cnt > 2) {
data.push(<div className="row" key={`extra${i}`}>{temp}</div>);
cnt = 0;
temp = [];
}
if (cnt <= 2) {
temp.push(
<div className="col-sm" key={i}>
<CardForPanel title={articles[i].title} tags={articles[i].tags} aid={articles[i].aid} openArticle={this.openArticle}></CardForPanel>
</div>
);
cnt ;
}
}
if(temp.length !=0){
data.push(<div className="row" key={`last one`}>{temp}</div>);
}
this.setState({
data: data,
});
} else {
throw new Error('Sorry could not verify you');
}
})
.catch((error) => {
alert(error.message);
});
}
render() {
if (this.props.authorized) {
return (
<div className="parent_container">
<TopmostTrayForPanel></TopmostTrayForPanel>
<div className="container">{this.state.data}</div>
</div>
);
} else {
return (
<Navigate to='/panel/articleverification' />
)
}
}
}
// Wrap and export
export default function(props) {
const navigation = useNavigate();
return <HomePageForArticalVerificationPanel {...props} navigation={navigation} />;
}
and below is my routing code
import React from "react";
import {Routes,Route} from 'react-router-dom'
import EditorPage from './components/editor/classbased/editorPage'
import LoginPageForArticalVerificationPanel from './components/panel/articleverficationpanel/classbased/loginPage'
import HomePageForArticalVerificationPanel from './components/panel/articleverficationpanel/classbased/homePage'
import ArticlePageForArticalVerificationPanel from './components/panel/articleverficationpanel/classbased/articlePage'
class App extends React.Component {
state = {
authorised:false,
extras:{}
}
authorizeUser = (authorizeState,extras) => {
console.log('called 1')
this.setState({
authorised:authorizeState,
extras:extras
})
}
render() {
return (
<>
<Routes>
<Route path='/editor' element={<EditorPage />} />
<Route path='/panel/articleverification' element={<LoginPageForArticalVerificationPanel authorizeUser={this.authorizeUser}/>} />
<Route path='/panel/articleverification/homepage' element={<HomePageForArticalVerificationPanel authorized={this.state.authorised}/>} />
<Route path='/panel/articleverification/articlepage' element={<ArticlePageForArticalVerificationPanel authorized={this.state.authorised}/>} />
</Routes>
</>
);
}
}
export default App;
CodePudding user response:
From what I can tell, after navigating to one of the nested routes and reloading the page, the app reloads and the authorized
state is reset and the child route component checks this state and imperatively redirects back.
Persist and initialize the authorized
state to/from localStorage.
class App extends React.Component {
state = {
// Read initial state from localStorage, provide fallback
authorized: JSON.parse(localStorage.getItem("authorized")) ?? false,
extras: {}
}
componentDidUpdate(prevProps, prevState) {
// Persist authorized state changes to localStorage
if (prevState.authroized !== this.state.authorized) {
localStorage.setItem("authorized", JSON.stringify(authorized));
}
}
authorizeUser = (authorizeState, extras) => {
console.log('called 1');
this.setState({
authorized: authorizeState,
extras: extras
})
}
render() {
return (
<Routes>
<Route path='/editor' element={<EditorPage />} />
<Route
path='/panel/articleverification'
element={(
<LoginPageForArticalVerificationPanel
authorizeUser={this.authorizeUser}
/>
)}
/>
<Route
path='/panel/articleverification/homepage'
element={(
<HomePageForArticalVerificationPanel
authorized={this.state.authorized}
/>
)}
/>
<Route
path='/panel/articleverification/articlepage'
element={(
<ArticlePageForArticalVerificationPanel
authorized={this.state.authorized}
/>
)}
/>
</Routes>
);
}
}