State lost when changing window.location.pathname
See original GitHub issueExpected behavior
The state to be preserved
Actual behavior
State is lost if window.location.pathname
is changed
Steps to reproduce behavior
I have this set up
// my main js file
app.router(route => [
route('/', mainView),
route('/game', gameView)
])
/*
* In my mainView I have a component like this
*/
const configPlayer = (state, send) => {
return html`
<div class="config-panel">
<input id="player" type="text">
<button onclick=${e => send('player:join')}>Play</button>
</div>
`
}
// the model for the view
module.exports = {
namespace: 'player',
state: {
name: '',
id: ''
},
reducers: {
/**
* set initial data
*/
init: (data, state) => {
console.log(JSON.stringify(data, null, 2))
return {
name: data.player,
id: '1'
}
}
},
effects: {
join: (data, state, send, done) => {
send('player:init',
{ player: document.getElementById('player').value },
done)
setTimeout(function () {
console.log(JSON.stringify(state, null, 2))
window.location.pathname = '/game'
}, 2000)
}
}
}
// and finally the called view
const gameView = (state, prev, send) => {
console.log(JSON.stringify(prev, null, 2))
return html`
<div class="container">
<h1>Hello ${state.player.name}!</h1>
<div class="board">
</div>
</div>
`
}
As you can see, clicking the button trigger the join
effect, that trigger the init
reducer and then change the pathname
. The init
and join
consoles log prints data correctly modified, but the one in the gameView prints the initial state if I log the state
and an empty object if I print prev
.
I’m not sure why the state is lost, but I think it wouldn’t happen if I make the redirect with choo router, I just don’t know how to access the router from a reducer or effect. I have seen examples using anchor tags but not changing the path from a model hook.
How can I access the router from effects/reducers? Is there a better way to navigate thru routes from a choo model?
Issue Analytics
- State:
- Created 7 years ago
- Comments:6 (4 by maintainers)
Top GitHub Comments
Thanks for the answer. I just manage to programatic navigate through my routes, thanks to this issue. I had to use this signature
'app:location
didn’t work, as the issue say, also send parameters are different because of the version of choo referred in the issue. Thanks for your feedback, I’ll close the issue.From my phone: if I’m not mistaken changing window.location.pathname causes a full page reload which indeed loses state - there’s an open issue for changing the state location, with a workaround included until this is solved (which should be soon; its a priority) - hope this answers your question! - cheers