In this post, we will see how to resolve “object is not iterable” error when processing similar responses in ReactJS project
Question:From the client I send a GET request to the laravel API:
ids– an array that can be empty.
idsis empty, on the server side, the controller returns a collection:
And in this case everything is ok
idsis not empty, on the server side, the controller returns other collection:
And in this case I get the error “typeerror response.data is not iterable”.
Why is that? How to fix?
Best Answer:As per the response logs, when sending API response from Laravel, The object being sent from Laravel is automatically converted to an array when the keys are in whole numbers and start with 0 to n without missing a digit. This indexing mechanism is the same as that of an array, due to this, the object gets converted to an array.
But when the indexing is random numbers and not a straight starting from 0, The keys cannot imitate the indexing of an array for that reason, it stays an object.
A quick fix from the front-end side is to wrap your
response.datato get an array of values like
Object.values(response.data)and then set them inside a state. This will make sure that the
response.datawill always be assigned as an array instead of an object.
A more better approach is to fix it on the laravel side to return array.
If you have better answer, please add a comment about this, thank you!