danial dehvan
danial dehvan

Reputation: 237

Can't use navigation.dispatch() inside useEffect

I am trying to prevent the user use the back button, I found a solution in the docs as they say, I must use this code:

navigation.dispatch(
    CommonActions.reset({
      index: 1,
      routes: [
        { name: 'Login' },
  
      ],
    })
  );

So I used it inside useEffect in order to apply it on page load.

useEffect(()=>{
  navigation.dispatch(
    CommonActions.reset({
      index: 1,
      routes: [
        { name: 'Login' },
  
      ],
    })
  );
},[])

But I am getting this error and the app does not work well:

Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

Upvotes: 1

Views: 790

Answers (1)

Iosif
Iosif

Reputation: 822

The problem is useEffect with [] is called when the component mounts. So the component mounts then you tell it to reset navigation to login page(same page) so Login gets remounted and useEffect called again. And so on and so on. So what you need to do is that the component that sends you to login needs to do the reset and remove it from useEffect inside the login Page.

Upvotes: 3

Related Questions