skip to Main Content

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:
enter image description here

how can I get the results I want without creating something like:

interface A {
  [key: string]: string;
  [key: number]: string;
}

2

Answers


  1. Chosen as BEST ANSWER

    I just changed the initial state from null to an empty object object and the error disappeared

    const [info, setInfo] = useState<Iinfo>({
      title: '',
      description: '',
      stars: 0
    

    })

    I don't quite understand how it works I would be very grateful if you could explain it to me


  2. Input is likely to provide type undefined in certain cases, you can do

    const change = (title: string,e: React.ChangeEvent<HTMLInputElement>) => {
       setInfo ({...info,[title]:e.target.value || ""})
    }
    

    adding

    || ""
    

    will pass an empty string if the value of e.target.value is undefined, solving the type problem

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search