skip to Main Content

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.

3

Answers


  1. You can try this:

    <Text>{exRates?.rates?.aud}</Text>
    

    or

    {exRates ? <Text>{exRates?.rates?.aud}</Text> : null }
    
    Login or Signup to reply.
  2. 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);
    }
    
    Login or Signup to reply.
  3. 🟢 Problem Solved !

    This is how you should access the JSON response.

    export const TestScreen = () => {
        
      const [exRates, setExRates] = useState(undefined);
      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(`${JSON.stringify(data)}`);
        console.log(`${JSON.stringify(data["rates"])}`);
        console.log(`${JSON.stringify(data["rates"]["usd"])}`);
        console.log('This is the API Call');
        setExRates(data);
      };
    
      useEffect(() => {
        loadData();
      }, []);
    
      return (
        <View style={styles.container}>
          <Text>Hello </Text>
          {exRates && <Text>{exRates["rates"]["usd"]["name"]} : {exRates["rates"]["usd"]["value"]}</Text>}
        </View>
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search