I have this interface defined as my state:
interface State {
id: string;
name: string;
description: string;
dimensionID: string;
file: File | null;
operator: string;
isFormValid: boolean;
filename: string;
};
I have a simple on change handler:
update = (event: React.FormEvent<HTMLInputElement>): void => {
const { name, value } = event.currentTarget;
this.setState({ [name]: value });
};
However, this error gets thrown:
Error:(109, 19) TS2345: Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'State | Pick<State, "id" | "name" | "description" | "dimensionID" | "file" | "operator" | "isFormValid" | "filename"> | ((prevState: Readonly<State>, props: Readonly<Props>) => State | Pick<...>)'.
Type '{ [x: string]: string; }' is not assignable to type '(prevState: Readonly<State>, props: Readonly<Props>) => State | Pick<State, "id" | "name" | "description" | "dimensionID" | "file" | "operator" | "isFormValid" | "filename">'.
Type '{ [x: string]: string; }' provides no match for the signature '(prevState: Readonly<State>, props: Readonly<Props>): State | Pick<State, "id" | "name" | "description" | "dimensionID" | "file" | "operator" | "isFormValid" | "filename">'.
My question is: How can I set state dynamically like how my on change handler tries? This handler is used for different parts of the form so I won't know which key of state I will need to update.
Update: SOLUTION From this post
update = (event: React.FormEvent<HTMLInputElement>): void => {
const { name, value } = event.currentTarget;
this.setState(prevState => ({
...prevState,
[name]: value,
}))
};
Works!
this.update.bind(null, name ). so that in the update function you have both name and event as parameters