reactjslaravelapi

"object is not iterable" error when processing similar responses in ReactJS project


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:

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:

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:

enter image description here

And in this case I get the error "typeerror response.data is not iterable".

Why is that? How to fix?


Solution

  • 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.