I want to use withPropsOnChange
to create a new debounced function based on the props that were passed in. If the props are changed, it should create a new function. withPropsOnChange
seems perfect for this, except that I need access to this.state
inside of the createProps
callback, which recompose doesn't provide.
What are the alternatives? i.e. how can I create a property (React or vanilla) that's contingent/depends-on on some other properties and is automatically updated when those props are updated?
Here's the gist of what I've got now:
class MyClass extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
isOpen: false,
isLoading: 0,
isWaiting: false,
searchQuery: '',
options: [],
value: undefined,
highlightedValue: undefined,
scrollPos: 0,
};
if(props.options) {
this.loadOptions = Lo.debounce(searchQuery => {
this.setState(state => ({
isLoading: state.isLoading + 1,
}));
props.options(searchQuery).then(result => {
this.setState(state => ({
isLoading: state.isLoading - 1,
options: result.options,
}));
});
}, props.delay);
}
}
}
As you can see, I'm defining a property called this.loadOptions
which is just a debounced copy of props.options
with some state handling.
This works adequately for now, but if the upstream modifies props.options
or props.delay
, then this.loadOptions
won't be updated because I'm only doing this in the constructor.
Now I could do all this again in componentWillUpdate
, but really I only want to do it if either props.options
or props.delay
are updated, because those are its only two dependencies.
I'm just looking for a cleaner design pattern to deal with this sort of thing. It's basically just "computed properties" now that I think about it (but I can't "recompute" it as needed -- I need the same instance back each time unless those properties are modified).