How to parse JSON data from API response using fetch in React Native

I’m working on a React Native app and trying to get data from an external API. The API call is successful and returns a 200 status code, but I can’t figure out how to extract the actual JSON data from the response.

My current code:

getWeatherInfo = () => {
    fetch("https://weatherapi.p.rapidapi.com/current.json?q=London", {
        "method": "GET",
        "headers": {
            "x-rapidapi-host": "weatherapi.p.rapidapi.com",
            "x-rapidapi-key": "my-api-key-here"
        }
    })
    .then(result => {         
        console.log(result);
    })
    .catch(error => {
        console.log(error);
    }); 
}

componentDidMount(){
    this.getWeatherInfo();
}

When I log the result, I can see the response object but not the actual JSON content. The API documentation shows it should return JSON data. What am I missing to access the response body data?

You need to call .json() on the response object to get the actual JSON data. Right now you’re just seeing the Response object with headers and status info, not the data itself. Also, add some error handling to catch failed requests.

Here’s your code fixed:

getWeatherInfo = () => {
    fetch("https://weatherapi.p.rapidapi.com/current.json?q=London", {
        "method": "GET",
        "headers": {
            "x-rapidapi-host": "weatherapi.p.rapidapi.com",
            "x-rapidapi-key": "my-api-key-here"
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(jsonData => {
        console.log(jsonData);
        // Process your weather data here
    })
    .catch(error => {
        console.log('Error:', error);
    });
}

The response.ok check catches errors like 404s or 500s.

You need to call .json() on the fetch response to get the actual JSON data. The response object just has metadata - you’ve got to parse the body separately. Here’s the fix:

getWeatherInfo = () => {
    fetch("https://weatherapi.p.rapidapi.com/current.json?q=London", {
        "method": "GET",
        "headers": {
            "x-rapidapi-host": "weatherapi.p.rapidapi.com",
            "x-rapidapi-key": "my-api-key-here"
        }
    })
    .then(response => response.json())
    .then(data => {
        console.log(data); // Log the actual JSON data
    })
    .catch(error => {
        console.log(error);
    });
}

The key part is adding .then(response => response.json()) before you process the data. This turns the response into a JavaScript object you can actually use.

totally! you gotta call .json() on the response to acutally get the json data. the fetch only gives the response object. don’t forget to check response.ok too, even if you’re getting 200! gl!