I have a controlled input component with some action on the value which is passed to local and redux state. At the moment on the onchange event im calling a function which "clean up" the value and then it send it to the local state and also send it to the redux state, as you can see in the following code.
componentDidUpdate(prevProps: Readonly<Props>): void {
if (this.props.value !== prevProps.value) {
this.updateInputValue(this.props.value);
}
}
handleOnChange = (e: ChangeEvent<HTMLInputElement>): void => {
const value = e.target.value || '';
if (value === '' || NUMBER_REGEX.test(value)) {
this.updateInputValue(value);
this.props.onChange(e);
}
};
updateInputValue = (inputValue: string): void => this.setState({ inputValue });
onChangeInputField = (e: any): void => {
const { alphanumeric, uppercase } = this.props;
if (trim) e.target.value = e.target.value.replace(/\s/g, '');
if (alphanumeric && ALPHANUMERIC_REGEXP.test(e.target.value)) return;
if (uppercase) e.target.value = e.target.value.toUpperCase();
this.updateInputValue(e.target.value);
this.props.onChange(e);
};
My concern here is that:
onChangeInputField triggers:
- updateInputValue which updates state value.
- props.onChange which updates redux store value
because something was updated, now we're calling componentDidUpdate which:
- Checks if received props are matching because we updated value in store with props.onChange, we're receiving new prop values
- because of that updateInputValue is once again triggered - which updates state again.
The problems i see here is that first of all we have multiple sources of truth Secondly i'm rerendering element multiple times.
what would be the correct flow?