Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined (reading 'avatar') – Reactjs

I’m trying to get data from a link (api) and show them on the page. When I run the project, I get this error.

The Users component code is as follow:

class Users extends Component {
constructor(props){
    super(props)
    this.state = { 
        users: [],
     }
}

 async componentDidMount(){
    const response = await axios.get('https://reqres.in/api/users');
    this.setState({users: response.data.data});
    // console.log(this.state.users);
 }

render() { 
    return (<>
        <button className="btn btn-primary">Create</button>
            <div className="row">
                {this.state.users?.map((user) => {
                            console.log(user);
                    return(
                        <div className="col-4">
                         <img src={this.user.avatar} alt="" />
                         <h4>{this.user.first_name} {user.last_name}</h4>
                         <h5>{this.user.email}</h5>
                         <div className="row">
                            <div className="col-6">
                                <button className="btn">Update</button>
                            </div>
                            <div className="col-6">
                                <button className="btn">Delete</button>
                            </div>
                         </div>
                        </div>
                    )
                }
                )}
            </div>
    </>);
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note: The api link (https://reqres.in/api/users) is correct and console log shows the outputs.

Could anyone help me?

>Solution :

I saw what is happening in your code.

<img src={this.user.avatar} alt="" />

In this line, you should change the src to user.avatar || "".

<img src={user?.avatar || ""} alt="" />

Hope this will work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading