1

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": "[email protected]",
    "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.

1 Answer 1

2

Update this line to the following.

{dataSource && dataSource[0] && dataSource[0].first_name}

This will ensure that dataSource[0] is not undefined.

the reason is that your fetch request is asynchronous so dataSource[0] is undefined until the response has been received.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked!!! It has been bugging me for weeks and I thought it I had to put them in variables or something. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.