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?
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?
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));
}}
/>
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>("").
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);
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