I'm trying to add an item conditionally into an array:
fields: [
...formPayload.fields.filter((field) => field !== oldValue),
...(!formPayload.fields.includes(newValue) ? newValue : null), //ERROR
],
But the last line gives the following error: type string | null must have a Symbol.iterator method that returns an iterator
If I replace the last line with
...newValue
It's working. What is wrong with my syntax?
CodePudding user response:
You just need to remove the spread operator from the second line:
// before:
...(formPayload.fields.includes(newValue) ? newValue : null),
// after:
(formPayload.fields.includes(newValue) ? newValue : null),
And if you want no value at all instead of null, you can use this syntax:
...(formPayload.fields.includes(newValue) ? [newValue] : []),