schiehll / react-alert

alerts for React
MIT License
608 stars 98 forks source link

Maximum update depth exceeded. #117

Closed mikhailrojo closed 5 years ago

mikhailrojo commented 5 years ago

Hello

why I get this error?

Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

this is my example

import React, { PureComponent } from "react";
import { withAlert } from "react-alert";

class Home extends PureComponent {
  componentDidUpdate(newprops) {
    this.props.alert.show('something')
  }

  render() {
    return (
        <button
          onClick={() => {
            this.props.alert.show("Oh look, an alert!");
          }}
        >
          Show Alert
        </button>
    );
  }
}

export default withAlert()(Home);

for some reason this.props.alert.show() invokes setState() infinitely

besLisbeth commented 5 years ago

Hi @mikhailrojo. The problem is in componentDidUpdate method. As soon as you remove it - your example will stop looping. Please, take a quick glance on componentDidUpdate in React docs

mikhailrojo commented 5 years ago

Sorry but this doesn’t answer my question... and it looks like a bug.

If I remove all my code- I wouldn’t have issues and warnings from react or react-alert...

Please reopen

besLisbeth commented 5 years ago

I'm really sorry, but the bug is not in the react or react-alert packages. Unfortunately, I posted the wrong link above but I just updated it.

If we've looked at the official 'react' documentation for the 'componentDidUpdate' method we'll see: image

That is what happened in your code - when component rerender it will loop the alert call. You need to add the condition in componentDidUpdate method like in the example, remove it totally or use another react lifecycle method.