Reputation: 125
I am trying to make a login form in react with typescript. But setEmail method is not accepting value. It says Argument of type 'string' is not assignable to parameter of type 'SetStateAction'. What should I do to solve it?
Upvotes: 5
Views: 21800
Reputation: 7985
You can set a string type for it
Explicit way:
const [email, setEmail] = useState<string>('')
or Implicit way:
const [email, setEmail] = useState('')
or if you want to set number type
const [inputNumber, setInputNumber] = useState<number>(0);
then in jsx
, do it this way
<input
type="number"
value={inputNumber}
onChange={(val) => {
//Some ways to do this
setInputNumber(Number(val.target.value));
setInputNumber(+val.target.value);
setInputNumber(parseInt(val.target.value,0));
}}
/>
Upvotes: 14
Reputation: 1269
you just need to use generic in this case with useState
hook
simple case
const [email, setEmail] = useState<string>("")
complex case
interface IUser{
email:string
}
useState
generic const [email, setEmail] = useState<IUser>({email: ''})
you can see DefinitelyTyped
Upvotes: 2
Reputation: 626
Initialize the useState with an empty string will solve.
useState can infer the type based on your initialState, thats why initialize with empty string will solve your case.
useState without initialState will be undefined, so your type and state is undefined.
If you want your state to have an more complex type, you need to pass a initialState with defined type:
const initialState: TYPE = {
// ...
};
const [state, setState] = useState(initialState);
or
Pass the type to useState without set type to initialState, like: useState<TYPE>(initialState);
Upvotes: 1
Reputation: 6992
Without any initial argument, the type of email
and setEmail
will be undefined.
const [email, setEmail]: [undefined, (value: ((prevState: undefined) => undefined) | undefined) => void] = useState();
So the first step is to enforce email to be a string by either using useState("")
or even better useState<string>("")
.
Upvotes: 1