I have several fields with data:
<input
type="text"
placeholder={`title`}
onChange={(e) => change(`title`,e)}
/>
<input
type="text"
placeholder={`description`}
onChange={(e) => change(`description`,e)}
/>
...
and only 1 state for all of them:
type Iinfo = {
title: string,
description: string,
stars: number
}
const [info, setInfo] = useState<Iinfo | null>(null)
I want that when the user enters something into the fields in the state, only the corresponding field is overwritten
const change = (title: string,e: React.ChangeEvent<HTMLInputElement>) => {
setInfo ({...info,[title]:e.target.value})
}
but typescript gives an error:
how can I get the results I want without creating something like:
interface A {
[key: string]: string;
[key: number]: string;
}
2
Answers
I just changed the initial state from null to an empty object object and the error disappeared
})
I don't quite understand how it works I would be very grateful if you could explain it to me
Input is likely to provide type undefined in certain cases, you can do
adding
will pass an empty string if the value of e.target.value is undefined, solving the type problem