Budhathoki1998
Budhathoki1998

Reputation: 125

How to use useState hook in React with typescript correctly?

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?

enter image description here

Upvotes: 5

Views: 21800

Answers (4)

Yoel
Yoel

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));
  }}
/>

see more examples

Upvotes: 14

Mhammed Talhaouy
Mhammed Talhaouy

Reputation: 1269

you just need to use generic in this case with useState hook

simple case

const [email, setEmail] = useState<string>("")

complex case

  • declare an interface
     interface IUser{
        email:string
        }
  • make useState generic
     const [email, setEmail] = useState<IUser>({email: ''})

you can see DefinitelyTyped

Upvotes: 2

Gabriel Alc&#226;ntara
Gabriel Alc&#226;ntara

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

Martin Seeler
Martin Seeler

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

Related Questions