Reputation:
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:
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?
Upvotes: 0
Views: 431
Reputation: 3826
Regarding the both of your issues, including this one:
I'm not sure how to observe any state change
You can use componentDidUpdate( prevProps, prevState ) callback, and determine inside, whenever the state was changed.
https://facebook.github.io/react/docs/component-specs.html#updating-componentdidupdate
Here you're trying to synchronize your local state with upper components. That's possible, but it's a hard thing to do it right. Especially when you will occasionally need to set some filter values from the top. Consider moving the state of the filter to the upper component.
To do that you will need to pass your state object and function used to update it instead of setState
as component props. State object would be stored as a part of the upper component state then.
You can use value links to make it look elegant. Here's what you code will look like in this case:
import { Link } from 'valuelink'
import { Input } from 'valuelink/tags.jsx'
const UpperComponent = React.createClass({
getInitialState(){
return {
filter : {
text : '',
...
}
}
},
render(){
return (
...
<Filter state={ Link.state( this, 'filter' ) } />
)
}
});
const Filter = ({ state }) => (
<div className="filter">
<Input valueLink={ state.at( 'text' ) } />
...
</div>
)
Here's an explanation of the technique: https://medium.com/@gaperton/state-and-forms-in-react-part-3-handling-the-complex-state-acf369244d37#.nuloz9adx
And here's the lib: https://github.com/Volicon/NestedLink
Upvotes: 0
Reputation: 3727
You can pass a callback to the this.setState(). see below:
_onStateUpdate() {
*Some code here*
}
onMinDateChange(minDate) {
this.setState({minDate}, _onStateUpdate);
},
Upvotes: 2