Getting old state in lifecycle events of ionic (using React)

Hey there
I am using Ionic with React for my App.

I have a strange bug and i dont know if i am doing something wrong or using something in the wrong way…
I googled like 10 hours and didnt find anything which explains this behavior…

Short version:
Inside of the event ionViewDidEnter i get an old state/prop of the component/page i am entering…

Short example:
I use ionViewDidEnter to initialize the page when i enter it the first time…
after first init i call setInitGame(true) so when i enter the page a second time i wont reInit the game…

The value is changed everywhere except inside of the lifecycle-events of ionic…
I dont know why this happens or why this is… is it maybe something with the router outlet?

I am using a global state and i connect to the stuff i need out of the global state like this in every component:

 export default connect<{}, StateProps, DispatchProps>({
  mapStateToProps: (state) => ({
  mapDispatchToProps: {
  component: React.memo(JustEnough)

When i use something like this… inside of my component for debugging:

  useEffect (() => {
    console.log("InitGame: " + initGame);
  }, [initGame]);

I can see, that initGame gets updated correctly…
but when i use initGame (and other stuff) inside of ionViewWillEnter i get values which do not correspond to the latest global state… it seems, that i get old states…

So i enter the page with initGame == false then i call setInitGame(true) (i can debug this in my whole app in every component it changed!!! even in the one i am right now… but if i leave the page and i debug initGame inside of ionViewDidLeave or in ionViewWillLeave then it is still false !!!

This also happens with other data…
I have a player array
I enter a game for the first time --> fine
I go back to lobby and delete some players–> state updated correctly!
I go back to the game --> inside of ionViewDidEnter the deleted players are there again…

This bug seems only to happen inside of the lifcycles events of ionic… Why is that?

If you need more information i will post it.

Thanks in advance

Hey Rabter,

I just ran into a similar issue, using useIonViewDidEnter. It looks like the callback passed to that function only has access to the initial state values, not the updated values.

I would suggest using useEffect with an empty array - this effect will only run when the component is initialized, basically doing the same thing as IonViewDidEnter.

useEffect (() => {
}, []);

Did you find a solution for this?

Hi, it’s quite late, but I had a similar problem and solved it with a reference instead of a state value.
My context: all ion accordions are opened on first page view and the constellation “open/closed” is saved when leaving the page and set again when coming back.

1 Like