I am trying to fetch data from an API. Fetch is obtaining the data fine, which is no issue. My problem is now simply trying to render specific values from that data. For some reason the data hasnt fully been loaded to the variable when trying to render the component and hence when it is trying to access the specific value, it comes up with the error TypeError: Cannot read properties of undefined (reading 'aud')
. I dont believe it is a problem specific to React Native, but maybe even React.js in general.
Here is the source code for what im trying to implement
export const TestScreen = () => {
const [exRates, setExRates] = useState([]);
const [loading, setLoading] = useState(true)
const loadData = async () => {
const res = await fetch(
"https://api.coingecko.com/api/v3/exchange_rates"
);
const data = await res.json();
console.log("This is the API Call");
setExRates(data);
}
useEffect(() => {
loadData();
}, []);
return (
<View>
<Text>Hello </Text>
{console.log("I am in the return section of the code")}
{console.log(exRates)}
<Text>{exRates.rates.aud}</Text>
</View>
);
};
Whats interesting is that when leaving the code as ive got it, loadData
doesnt seem to run as the console log for that function and doesnt seem to log what ive instructed. And the exRates
variable doesnt have data
So it seems like it is trying to render the code before allowing the loadData
function to run through useEffect
. And it is also running the return twice (I dont know why, if someone can direct me as to why also thatll be great!)
But then when I coment out the <Text>{exRates.rates.aud}</Text>
element it seems to run the loadData
function. Here is the console when this is commented out.
Mind you, as Im writing this, the behaviour is changing everytime i refresh the app. Sometimes it wil have the rates data in both console logs, sometimes it will error out sometimes it wont. I’m at a loss here. Any help would be greatly appreciated.
3
Answers
You can try this:
or
Free plan is rate limited. When a call hits the limit, it returns 429 Too Many Requests.
Check that a response is ok, before using it.
🟢 Problem Solved !
This is how you should access the JSON response.