Reputation: 8470
I have this handleSelect:
const handlerSelectBank = (event: React.ChangeEvent<{ value: unknown }>) => {
setState({
...state,
buttonDisabled: false,
selectedBank: event
});
};
But I got this error:
Type 'ChangeEvent<{ value: unknown; }>' is not assignable to type 'null'.ts(2322)
This is the initial value of state:
const defaultState = {
buttonDisabled: true,
selectedBank: null
};
What type should I use on event
?
Upvotes: 0
Views: 3533
Reputation: 42298
is not assignable to type 'null'
Your state is defined such that selectedBank
can only be null
and anything else will give an error. Since your defaultState
has selectedBank: null
, Typescript will infer the type for this property as null
unless you tell it otherwise.
You can declare the type for the state either by assigning a type to the defaultValue
variable
const defaultState: MyState = {
or the generic on the useState
hook
const [state, setState] = useState<MyState>(defaultState);
You just need one of those, not both.
The type for MyState
should be such that selectedBank
can be null
, but can also be the value that you want.
I am assuming that the react-select tag means you are using the react-select package? Different packages and components define their own change event types. react-select calls onChange
with two arguments which are the option and an ActionMeta
object.
import React, { useState } from "react";
import Select from "react-select";
interface Bank {
label: string;
value: string;
}
type MyState = {
buttonDisabled: boolean;
selectedBank: Bank | null;
};
export const MyComponent = ({ options }: { options: Bank[] }) => {
const defaultState: MyState = {
buttonDisabled: true,
selectedBank: null
};
const [state, setState] = useState(defaultState);
function handlerSelectBank(selectedBank: Bank | null) {
setState({
...state,
buttonDisabled: false,
selectedBank
});
}
return (
<Select
value={state.selectedBank}
options={options}
onChange={handlerSelectBank}
/>
);
};
It might be easier to have separate useState
hooks for separate pieces of data.
Upvotes: 0
Reputation: 434
I also use TypeScript and React. Try this Event type:
function handlerSelectBank (e: React.FormEvent<HTMLSelectElement>) {
setState({
...state,
buttonDisabled: false,
selectedBank: e.currentTarget.value
})
}
More info: https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement
Upvotes: 1