Skip to content Skip to sidebar Skip to footer

Method Renders Correctly When Triggered One At A Time, But Not Using _.map In React-redux Container

I have React-Redux container where a bunch of buttons are dynamically generated. Below them are Select All and Clear Selection buttons. When a button is clicked, it is sent to a me

Solution 1:

There might be some other problems with the code, but one problem that can explain this behavior is that the updater-object parameter cuts to the setState call refers to this.state.

A setState call in a React event handler does not immediately update the state, but rather queues the update. At some point after your event handler finishes, these batched updates are processed to compute the new state. This means that when you call onCutSelect multiple times, you queue a series of updates, which each replace cuts by a clone of the original cuts with only one cut updated. When these updates are processed, the last update wins, and only the last button is selected.

The solution is to use an updater function instead of an object:

this.setState((prevState, props) => ({/* state update */})) (see the setState docs).

The updater function will get the up-to-date state resulting from applying previous updates, so you can incrementally update each cut. In your code you can do something like this:

onCutSelect(cut) {
    this.setState(
      ({cuts: prevCuts}) => ({cuts: {...prevCuts, [cut]: cut}}),
      () =>this.props.basicQueryResults(this.state.cuts)
    );
}

Also, if this.props.data is an array, you can simply use this.props.data.map((c) => ..). No need to use lodash or underscore.

Post a Comment for "Method Renders Correctly When Triggered One At A Time, But Not Using _.map In React-redux Container"