skip to Main Content

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


  1. find() returns undefined if it can’t find anything.

    undefined is not compatible with your typing. So you should only append it here is something to append:

    function handleSelectValue(id: string) {
          const findResult = DefinedArray.find(x => x.id);
          if (findResult) {
                setValue([...Value, ...findResult ]);
          }
      }
    

    Or you could spread an empty array as fallback, if that’s more readble:

    setValue([ ...Value, ...(DefinedArray.find(x => x.id) || []) ]);
    
    Login or Signup to reply.
  2. If you are sure that the item exists you can do either of these:

    function handleSelectValue(id: string) {
      setValue([...Value, DefinedArray.find((x) => x.id)!]);
    }
    

    or

    function handleSelectValue(id: string) {
      const item = DefinedArray.find((x) => x.id)
      if (!item) throw new Error('this will never happen')
      setValue([...Value, item]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search