React js Typescript Argument of type 'string' is not assignable to parameter of type 'SetStateAction<number>'
Asked Answered
G

1

7

Hello I'm having this error:

Argument of type 'string' is not assignable to parameter of type 'SetStateAction<number>'.

this is a part of my code:

.
.
.
const[ idPadre, setIdPadre ] = useState<number>(0);
.
.
.

<select 
       onChange={ (e) => setIdPadre( e.target.value ) }
       value={ idPadre }
>
<option value="">Select...</option>
       {data.map((item) => {
                            return <option key={item.id}
                                    value={ item.id }
                            >{item.description}</option>
                            })}                                
</select>

so, I'm adding data from file json and I want that select an item and value get id.

Gaitskell answered 28/4, 2021 at 14:41 Comment(1)
setIdPadre( e.target.value ) the value e.target.value potentiolly is a string not a number as you set in your useState<number>(0);. Either ParseInt it or set useState to string not a number or if you want to accept both string and numbers then do useState<number | string>(0);Revers
O
11

The error is pretty descriptive. You cannot pass parameter of type string into the useState hook which expects number.

You're calling the setIdPadre hook with the e.target.value variable, which is a string.

What you can do instead is convert the value into a number:

{ (e) => setIdPadre( parseInt(e.target.value) ) }
Overabound answered 28/4, 2021 at 14:48 Comment(1)
hey @val, I am getting a similar error when trying to use a JSON file, something like this: export const CTASection = () => { const {t, i18n} = useTranslation( {keyPrefix: ("homepage.ctaSection")} )Bevon

© 2022 - 2024 — McMap. All rights reserved.