Im hosting a react-app on gitlab pages and i use react-router for routing between pages using historyRouter. The routing works fine, but when i reload (hit f5) or open a route directly by pasting the url into my adressbar, the site loses their whole state. It means, e.g im at myaccount.gitlab/mysite and i hit any link which redirects me to myaccount.gitlab/mysite/nextpage using this method,
this.props.history.push("/nextpage", {
mystate: this.state.mystate
})
i push also the state mystate to this page. Everything works fine until now, but if i try to reload the page i get an emtpy page. Debugging in console tells me that this.location.state is undefined. I successfully dirty fixed this issue by telling the constructor of nextpage, to set this.location.state to any default value if it is undefined or null. Now i can reload the page successfully but any state is gone.
Is there anything to fix this behaviour? Is this only a gitlab issue? I can run my app locally in development and in production mode at localhost and there are no problems losing any state or something else. Followed some additional code i used:
Gitlab-cli.yml:
test:
image: node:9.6.1
stage: test
script:
- npm install; npm run test
pages:
image: node:9.6.1
stage: deploy
variables:
PUBLIC_URL: "/mypage"
script:
- rm package.json; mv package.json.pages package.json;
npm install;npm install react-scripts@1.1.1 -g;npm run build
- rm -rf public; mv build public
artifacts:
paths:
- public
only:
- master
index.js:
import { Switch, Route, BrowserRouter as Router } from "react-router-dom";
const routing = (
<Router basename={process.env.PUBLIC_URL}>
<div>
<Switch>
<Route exact path="/" component={main} />
<Route path="/nextpage" component={nextPage} />} />
<Route component={PageNotFound} />
</Switch>
</div>
</Router>
);
ReactDOM.render(routing, document.getElementById("root"));
I believe that it's not gitlab related issue. it makes sense, in the first scenario you are going from main page to nextPage passing an argument myState so it is available to the nextPage through props. while in the second one you are coming from nowhere, so the history is not aware of myState.
one solution is to simply use lolacstorag
main.js
// instead of:
/*this.props.history.push("/nextpage", {
mystate: this.state.mystate
})
*/
// do:
localStorage.setItem('myState', JSON.stringify(this.state.myState));
nextPage component
export default class nextPage extends React.Component{
//...
componentDidMount(){
// grap it from localStorage:
let myState = JSON.parse(localStorage.getItem('myState'));
// do whatever you want with it,
// it will be available unless you unset it
}
/... rest of your code..
}