2

I have child component with an HTML element that triggers a callback from it's parent function on click. The callback then changes the state in the parent component. The changed state is then sent back down to the parent which is used in the conditions of the if statements below. toggle, a prop from the parent, then dispatches an action that changes a value in the store. However, this dispatch ends up changing the store, and thus one of the props in the parent component, which is also passed down to the child component.

As a result, when I insert this in to my code, I get an infinite loop.

  /* no state changes to the current component */
  componentWillUpdate(nextProps) {
    const {
      // ... some props
      toggle, // func
    } = nextProps;

    if (/* case 1 of 2*/)
      toggle(true);
    } else (/* case 2 of 2 */) {
      toggle(false);
    }
  }

Because the onClick triggers a callback that changes a field in the parent's state that the if statement above relies on, I have to throw the if statement in componentWillUpdate (or some React API where I can execute the if statement once I'm sure the change to the parent's state is complete (as opposed to putting it with the onClick function call).

I want to trigger the above only once after an on-click. I don't want it to loop infinitely. How can I do this?

TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114

2 Answers2

5

I don't want it to loop infinitely. How can I do this?

By comparing values in props to nextProps. So you're only toggling when you need to. Hard to provide exact code without knowing your current logic.

if (this.props.src !== nextProps.src) {
  // toggle logic
}

Also, you probably want to do this inside of componentWillReceiveProps instead, so you don't potentially render before your toggle has occured.

Jack
  • 20,735
  • 11
  • 48
  • 48
0

It's your toggle changing the state after a state change that is causing the loop not the on-click.

You should be able to modify the state properties that affect the logic for the toggle at the same point that the onClick is makes it's state changes.

Doing this the state will already have it properties set correct and you need only execute the non-state related behaviour of toggle().

Pineda
  • 7,435
  • 3
  • 30
  • 45
  • But the function triggered in `onClick` is also a callback (a prop) that changes state in the parent. So, I'm not sure if React will just interrupt the onClick and proceed with the callback, or if it will finish the rest of the code in the onClick (if I were to put the code with the onClick). – TheRealFakeNews Feb 08 '17 at 00:46
  • It's ok the `onClick` changes the state. At this point _maybe_ it's possible to add the `state` change contained within `toggle()` as well (since that logic relies on `state` too). Therefore when toggle is invoked it doesn't cause another `state` change and breaks the infinite loop. – Pineda Feb 08 '17 at 01:00