Search code examples
react-nativereduxes6-promisefetch-apireducers

How can I get the nested elements of JSON array from fetch API?


I am trying to get some data from server using fetch api in React Native. How can I get it in the JSON format with all fields showing including the nested ones?

I have already tried converting into JSON after getting data from the promise. However, the data is not properly formatted. Fetching the same data using postman gives me all the data and fields populated.

My fetch api looks like this:

fetch("https://someurl.com/apps/api/", {
    method: "GET",
    headers: {
      api_key: "somekey",
      "Content-Type": "application/json"
    },
    params: JSON.stringify({
      device_latitude: deviceLat,
      device_longitude: deviceLong
    })
  })
    .then(response => response.json())
    .then(restData => {
      dispatch({
        type: FETCH_REST,
        payload: restData
      });
    })
    .catch(error => {
      console.error(error);
    });

This is my response data from fetch api when I am doing a console log on restData in my reducer:

[  
   Object {  
      "restID":1,
      "name":"Rest1",
      "restLocation": null
   },
  Object {  
      "restID":2,
      "name":"Rest2",
      "restLocation": null
   }
]

Below is the result when I am calling the endpoint using Postman.

Note: the restLocation field below has more data which is not present when using the fetch api as above:

[  
   {  
      "restID":1,
      "name":"Rest1",
      "restLocation":{  
         "id":2,
         "distance":2
      }
   },
   {  
      "restID":2,
      "name":"Rest2",
      "restLocation":{  
         "id":3,
         "distance":1
      }
   }
]

Solution

  • GET parameters should be url encoded and put into the fetch url.

    For example GET /test with postman PARAMS foo1=bar1 and foo2=bar2 should send a GET request to /test?foo1=bar1&foo2=bar2.

    We can encode your params {device_latitude: deviceLat, device_longitude: deviceLong} as follows:

    const url = `https://someurl.com/apps/api/?device_latitude=${deviceLat}&device_longitude=${deviceLong}`;
    const fetchableUrl = encodeURI(url);
    

    Then fetch it in the same way but drop the params because they belong in the url:

    fetch(fetchableUrl, {
        method: "GET",
        headers: {
          api_key: "somekey",
          "Content-Type": "application/json"
        }
    })
    .then(response => response.json())
    .then(restData => {
        dispatch({
            type: FETCH_REST,
            payload: restData
        });
    })
    .catch(error => {
        console.error(error);
    });