Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set a state variable to an empty array in React Typescript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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.

>Solution :

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) || []) ]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading