V
V
Vika Marmeladka2021-06-14 23:21:28
AJAX
Vika Marmeladka, 2021-06-14 23:21:28

Why do I get undefined at the beginning and only data after?

I have a component that makes an ajax request using the axios library and passes data to a child component. I used async and await for componentDidMount but it didn't help

. If I look in the logs I get the following:
60c7ba048eb5e932838785.png

Parent component

import React from "react";
import Instagram from "./Instagram";
import * as axios from "axios";

class InstagramContainer extends React.Component {
    constructor(props) {
        super(props)

        this.state = { images: {} }
    }

    async componentDidMount() {
        await axios.get('https://jsonplaceholder.typicode.com/photos')
        .then(response => {
            this.setState({
                images: response.data,
            })
        })
    }


    render() {
        return <Instagram images={this.state.images}/>
    }
}

export default InstagramContainer

child component
import React from 'react'
import styles from './Instagram.module.scss'

class Instagram extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        console.log(this.props);

        return(
            <div className={styles.Instagram}>

            </div>
        )
    }
}

export default Instagram;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-06-14
@Aleksandr-JS-Developer

Because the request turns out to be asynchronous and undefined at the time of loading

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question