4

I am using react-redux and redirecting users based on the value of prop. How can I handle the error produced in the console?

I have used useEffect to push users to different components based on props. I'm not sure if this is the correct way to do this.

  useEffect(() => {
    if (isAuthenticated) {
      history.push("/");
    } else if (signup) {
      history.push("/signup");
    }
  });

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Freddy.
  • 1,593
  • 2
  • 20
  • 32
  • That warning may be due another reason. It is saying that you are trying to set the state of your current component after rendering the `signup` component. – Muhammad Zeeshan Jan 27 '20 at 09:27
  • check here https://stackoverflow.com/questions/53949393/cant-perform-a-react-state-update-on-an-unmounted-component – ANIK ISLAM SHOJIB Jan 27 '20 at 09:27

3 Answers3

1

If we providing isAuthenticated variable to useEffect then it will only run if isAuthenticated is change

 useEffect(() => {
    if (isAuthenticated) {
      history.push("/");
    } else if (signup) {
      history.push("/signup");
    }
  },[isAuthenticated]); // pass isAuthenticated it will check changes of isAuthenticated and run our useEffect callback if changes found
Prakash Karena
  • 2,525
  • 1
  • 7
  • 16
1

useEffect() : after and for every render cycle

useEffect(() => { }); //without any arguement acts as componentDidUpdate

useEffect(() => { }, []); //with empty array arguement acts as componentDidMount

(runs only once after first render)

 useEffect(() => {
    if (isAuthenticated) {
      history.push("/");
    } else if (signup) {
      history.push("/signup");
    }
  },[isAuthenticated]); //passing a value will remove the error that you are receiving and check for the variable responsible for change , if changes are found it will run useEffect callback.
0

I've been able to overcome this error by wrapping the history.push call in a setTimeout. It's definitely not ideal, but I've yet to get to the root of the issue. I'll post an update when I do, but for now, you can use...

useEffect(() => {
  if (isAuthenticated) {
    setTimeout(() => {
      history.push("/")
    }, 0);
  } else if (signup) {
    setTimeout(() => {
      history.push("/signup");
    }, 0);
  }
});
Mike T
  • 513
  • 5
  • 14