The error “Type ‘string[] | undefined’ must have a ‘[Symbol.iterator]()’ method that returns an iterator” occurs in typescript when we try to spread an array but never provide the initial value to the state.
Why this error occurs ?
Suppose you have a state where you want to store an array and this array contains two items that you want to keep track of :
1. previous values, using spread operator.
2. a new array called numbers.
The error occurs when the state has no initial value. This error message shows that the state does not know where to start or what value to use. In other words, the state needs an initial value to be defined so that it can be initialized properly. In React, this can be done by assigning an initial value to the state when it is declared. By providing an initial value, the state knows where to start and can be updated accordingly throughout the lifecycle of the application.
const [state, setState] = useState<number[]>()
const numbers = [1, 2, 3, 4];
// ⛔️ Error: Type 'string[] | undefined' must have a '[Symbol.iterator]()' method //that returns an iterator
setState([...state, ...numbers])
Solution for the error –
To resolve the error you just need to provide the initial value to the state,
one common solution is to set the initial value to an empty array.
Now, when the state is declared, it already has a starting value and the error message is no more. In React, this can be done by defining the state with an initial value of an empty array like so:
const [state, setState] = useState<number[]>([])
const numbers = [1, 2, 3, 4];
setState([...state, ...numbers])