Search code examples
reactjsreact-nativeapirender

React Native undefined is not an object(evaluating 'data[0].given_amount')


I am having this code and when I open this screen I am having error undefined is not an object(evaluating 'data[0].given_amount'), and when I am already on that screen it loads informations from api, but when I open that screen I have this Render error.

 import React, { useEffect, useState } from 'react';
    import {
        View,
        Text,
      
    } from 'react-native';
    import { styles } from './style';
    import Colors from '../../constants/colors';
    import { useTranslation } from 'react-i18next';
    import * as api from '../../core/api';
    import BackHeader from '../../components/backheader/backheader';
    
    const Ethstaking = props => {
        const { t } = useTranslation();
        const [data, setData] = useState([]);
    
    
        const stakingInfo = async () => {
            let res = await api.stakingInfo();
            console.log("ethstake------", res.data.data)
            //console.log("ethstake------", res.data.data[0]['given_amount'])
            setData(res.data.data);
    
        }
        useEffect(() => {
            stakingInfo();
    
        }, []);
    
        return (
    
            <View style={{ flex: 1, backgroundColor: Colors.white }}>
                <BackHeader name={t('ethstake')} navigation={props.navigation} />
    
                <View style={styles.Container}>
    
                    <View style={styles.card}>
                        <Text style={styles.row}>{t('givenamt')}:  {data[0].given_amount}</Text>
                        <Text style={styles.row}>{t('lastincome')}:  {data[0].yesterday_income}</Text>
                        <Text style={styles.row}>{t('totalincome')}:  {data[0].total_income}</Text>
                        <Text style={styles.row}>{t('totaleth')}:  {data[0].total_eth}</Text>
    
                    </View>
                </View>
            </View>
        );
    
    };
    
    export default Ethstaking;

In console I have

ethstake------ [{"given_amount": "0.062000000", "total_eth": "0.062232910", "total_income": "0.000232910", "yesterday_income": "0.000004710"}]

Solution

  • I solved it by

    setData(res.data.data[0]);
    
     <Text style={styles.row}>{t('givenamt')}:  {data.given_amount}</Text>
     <Text style={styles.row}>{t('lastincome')}:  {data.yesterday_income}</Text>
     <Text style={styles.row}>{t('totalincome')}:  {data.total_income}</Text>
     <Text style={styles.row}>{t('totaleth')}:  {data.total_eth}</Text>