Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all articles
Browse latest Browse all 28463

How to display data from API in React Native without error undefined property?

$
0
0

I always get undefined property error when I use dataSource[0].first_name in displaying.

export default class Profile extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            dataSource: []
        }
    }
    async componentDidMount() {
        const response = await fetch('http://api url goes here /api/v1/getUserInfo/40', {
            method: 'GET',
            headers: {
                'authorization': 'token ' + global.storeToken,
            }
        })
            .then((response) => {
                return response;
            })
            .catch((error) => {
                alert('Error!' + error)
            })

        const json = await response.json();
        this.setState({
            isLoading: false,
            dataSource: [json],
        });
    }

    render() {
        const { dataSource } = this.state;

        return (
            <Container>
                <Header span style={styles.headerStyle}>
                    <Body style={{ justifyContent: "center" }}>
                        <Label style={styles.labelNickname}></Label>
                        <Label style={styles.labelUserID}> {dataSource[0].first_name}</Label>
                    </Body>
                </Header>
            </Container>
        );
    };
}

The api content is:

{
    "id": 40,
    "email": "kk@gmail.com",
    "first_name": "Kagura",
    "last_name": "Kinomoto",
    "birth_date": "1990-01-01T00:00:00.000Z"
}

There's always error.

TypeError: Cannot read property 'first_name' of undefined

This error is located at:
    in Profile (at SceneView.js:9)
    in SceneView (at StackViewLayout.tsx:898)
    in RCTView (at View.js:35)
    in View (at StackViewLayout.tsx:897)
   etc...

What's weird is it worked yesterday after all the console logs and stuff. I only hibernated the laptop, when I tried to run it again today, the error came back.


Viewing all articles
Browse latest Browse all 28463

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>