Home > Blockchain >  React Native rendering fetch API data
React Native rendering fetch API data

Time:10-26

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.

enter image description here

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

enter image description here

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.

enter image description here

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.

CodePudding user response:

You can try this:

{exRates?.rates?.aud}

or

{exRates ? {exRates?.rates?.aud} : null }

CodePudding user response:

Free plan is rate limited. When a call hits the limit, it returns 429 Too Many Requests.

Our free API has a rate limit of 10-50 calls per minute, if you exceed that limit you will be blocked until the next 1 minute window. Do revise your queries to ensure that you do not exceed our limits should that happen.

Check that a response is ok, before using it.

if (res.ok) {
  const data = await res.json();
  setExRates(data);
}
  • Related