0
votes

I am trying to write an application that uses a toastr component. However, when I try and dispatch a redux action in this component I get the following console message:

Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

You can see an example of this in this codesandbox. Particularly, the issue is at the toastr.js component at line 23. Thanks!

1

1 Answers

2
votes

The problem is exactly what the error message says: you're triggering a form of React state update directly inside of a render() method:

const Toasts = ({ appointments, resetState, toastedAppointment, toasts }) => {
  if (toasts.type) {
    switch (toasts.type) {
      case "dataFetched":
        resetState(); // Dispatching this action creates the warning.

In this case it's dispatching a Redux action, but that ultimately results in a React setState() call.

Don't do that :) Side effect logic, like triggering some kind of additional update based on current state, should probably happen in something like componentDidUpdate. The Toasts component would probably need to be converted from a function component to a class component accordingly.