I have a simple useState function that looks like this:
const [value, setValue] = useState<values[]>([]);
Theoretically, this will mean that the state of value
defaults to an empty array.
I then have a function that I’ve defined like this:
function handleSelectValue(id: string) {
let fakeArray:Array<values> = [...Value, DefinedArray.find(x => x.id)]
setValue(fakeArray);
}
I also tried:
function handleSelectValue(id: string) {
setValue([...Value, DefinedArray.find(x => x.id)]);
}
I would think that this code should work, however, I get an error that says
Type ‘Value | Undefined’ is not assignable to type ‘Value’. Type ‘Undefined’ is not assignable to type ‘Value’.
I’m not sure where, exactly, the undefinedness is coming from. It seems to me that my default value of "value" is defined as an empty array of value. (Value is defined elsewhere, to be clear, with a Guid, a name, and a few other descriptor fields).
What is wrong with this code here? I know stateful arrays can be a bit wonky, but this seems pretty straightforward to me.
2
Answers
find()
returnsundefined
if it can’t find anything.undefined
is not compatible with your typing. So you should only append it here is something to append:Or you could spread an empty array as fallback, if that’s more readble:
If you are sure that the item exists you can do either of these:
or