Ajith Kumar
Ajith Kumar

Reputation: 7

Results of API request using axios returns undefined in my React Native code but logs correctly in Console

My below code prints the response in Console but when updating it to results using setResults method of useState, it does not work. It prints nothing in place of result.length in my JSX code.

import React, { useState } from 'react';
import {Text, View, StyleSheet,Button } from 'react-native'
import axios from 'axios'
const WeatherAPI = () => {
const [ results, setResults] = useState([]);

const getAPIresults = async () => {
    await axios.get("https://newsapi.org/v2/top-headlines?country=us&apiKey=<mykeyhere>")
        .then((response)=>{
            console.log(response);
            setResults(response);
          })
          .catch((error)=>{
            console.log(error)
          })    
}
return(
<View>
<Text> We got {results.length} items</Text>
<Button title="GetAPI" onPress = {() => {getAPIresults()}} />
</View>
)
}

I initialized an empty array to results, but the response would be an object. So, I tried to assign an array instead of an object. It doesn't matter in React but I tried to update an array that is present in the response object.

response json object has articles array

const getAPIresults = async () => {
    await axios.get("https://newsapi.org/v2/top-headlines?country=us&apiKey=<mykeyhere>")
        .then((response)=>{
            console.log(response.articles);
            setResults(response.articles);
          })
          .catch((error)=>{
            console.log(error)
          })    
}

but it throws an error saying results is undefined. Even the console throws undefined now. Error Attached. Can anyone help in resolving this issue? Thanks in Advance

Upvotes: 0

Views: 1473

Answers (1)

Guruparan Giritharan
Guruparan Giritharan

Reputation: 16354

When axios receives a response the data is contained in the data field of response, you should set the data as below.

 setResults(response.data.articles);

Upvotes: 1

Related Questions