Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Body.json() on response loses nested arrays

import 'whatwg-fetch'

The incoming response looks like this (grabbed from proxy):

"data": {
    "category_tree": [
        {
            "category_id": "1",
            "name": "A",
            "children": [
                {
                    "category_id": 2
                    "name": "B, child of A",
                    "children": [
                        {
                            "category_id": 3,
                            "name": "C, child of B",
                        }
                    ]
                }

            ]
        }
    ]
}

And the handler works like this:

.then( response => response.json())

.then( json => dispatch({
    type: RECEIVE_DATA,
    data: json
}))

But by the time the response.json() promise resolves, the data has already lost all of it's nested arrays:

"data": {
    "category_tree": [
        {
            "category_id": "1",
            "name": "A",
            "children": []
        }
    ]
}

Any ideas for having this not happen?

Edit: the response header I am getting:

HTTP/1.1 200 OK
Server: nginx/1.10.2
Date: Thu, 12 Apr 2018 09:38:32 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/7.1.15

Edit2: request code currently looks like this:

const fetchCategories = () => {
    return dispatch => {
        dispatch({
            type: FETCH_CATEGORIES_REQUEST
        })

        return fetch(
        `${SERVICE_API_BASE_URL}/api/categorytree?ope_flg=1`)
            .then(
                response =>  response.json(),
                error => console.log("error in fetch cat", error)
            )

            .then(
                json => console.log(json) || dispatch({
                    type: FETCH_CATEGORIES_RESPONSE,
                    categories: json
                })
            )
            .catch(
                ex => console.log("parsing failed", ex)
            )
    }
}
like image 582
Daniel Thompson Avatar asked Sep 18 '25 05:09

Daniel Thompson


1 Answers

The response needed to be first interpreted as text, and then parsed as JSON. From the mozilla docs on "the body mixin for the fetch API":

Body.text() Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text). The response is always decoded using UTF-8.

Perhaps .json() was failing because of some encoding issue? I did try changing the Content-Type to Content-Type: application/vnd.api+json but that didn't seem to help.

like image 186
Daniel Thompson Avatar answered Sep 19 '25 18:09

Daniel Thompson