• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: “object is not iterable” error when processing similar responses in ReactJS project

Resolved: “object is not iterable” error when processing similar responses in ReactJS project

0
By Isaac Tonny on 03/04/2023 Issue
Share
Facebook Twitter LinkedIn

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.
If ids is empty, on the server side, the controller returns a collection:
And this is the response from the server I get:
enter image description here
And in this case everything is ok
If ids is not empty, on the server side, the controller returns other collection:
And this is the response from the server I get:
enter image description here
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.data to get an array of values like Object.values(response.data) and then set them inside a state. This will make sure that the response.data will 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!

Source: Stackoverflow.com

api laravel reactjs
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to stop a thread that has a blocking function from easygui in python

05/04/2023

Resolved: Removing null keys from a json array of objects

05/04/2023

Resolved: How can I generate at compile-time a separate OpenAPI Swagger.json file for each Controller in my ASP.NET project?

05/04/2023

Comments are closed.

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.