From the client I send a GET request to the laravel API:
axios
.get(
config.apiUrl + "/api/news",
{
params: {
ids: ids
}
}
)
.then((response) => {
setNews([...news, ...response.data]);
})
.catch((error) => {
console.log(error);
return false;
})
ids
– an array that can be empty.
If ids
is empty, on the server side, the controller returns a collection:
News::with('source:id,title,url')->orderByDesc('created_at')->limit(200)->get(
[
'created_at',
'custom',
'description',
'link',
'id',
'source_id',
'title'
]
);
And this is the response from the server I get:
And in this case everything is ok
If ids
is not empty, on the server side, the controller returns other collection:
News::with('source:id,title,url')->orderByDesc('created_at')->get(
[
'created_at',
'custom',
'description',
'link',
'id',
'source_id',
'title'
]
)->whereIn(
'id', $ids
);
And this is the response from the server I get:
And in this case I get the error "typeerror response.data is not iterable".
Why is that? How to fix?
3
Answers
As you can see, response.data is not array.
It’s an object.
You need to fix this. In Larvel site, return data as an array.
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 likeObject.values(response.data)
and then set them inside a state. This will make sure that theresponse.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.
The error "TypeError response.data is not iterable" occurs because when the ids
parameter is not empty, the Laravel controller is returning a single model instance (as seen in the response screenshot), rather than a collection. In JavaScript, you can iterate over an array or iterable object using a loop or a method like map(), filter(), reduce(), etc., but you can’t iterate over a single object directly.
To fix this issue, you can check whether the response data is a single object or an array, and handle each case accordingly. For example:
In this code, we’re using the Array.isArray() method to check if the response data is an array or not. If it’s an array, we can use it directly in the setNews() method. If it’s a single object, we need to wrap it in an array using the array literal [response.data], so that we can iterate over it.
With this modification, your code should work correctly in both cases where ids is empty or not.