zyklus zyklus - 3 months ago 22
React JSX Question

React state lifecycle for a filter component

I'm just looking for advice on how to properly set / read state in a component that is just a filter (i.e. select dates, min max values, etc).

I basically have:

onMinDateChange(minDate) {
this.setState({minDate});
},

onMaxDateChange(maxDate) {
this.setState({maxDate});
},

...


Now I want to call
this.props.onChange()
on every state change, but I have two issues:


  • state doesn't immediately update; how do I call this on the "next tick"?
    componentDidUpdate
    ?

  • I'm not sure how to observe any state change so that I don't have to write:

    onMinDateChange(minDate) {
    this.setState({minDate});
    this.update();
    },

    onMaxDateChange(maxDate) {
    this.setState({maxDate});
    this.update();
    },

    ...



Any help on both of these points?

Answer

You can pass a callback to the this.setState(). see below:

_onStateUpdate() {    
  *Some code here* 
}


onMinDateChange(minDate) {   
      this.setState({minDate}, _onStateUpdate); 
},
Comments