DEV Community

Cover image for Day 34: Consuming a RESTful API with React
Matt Ryan
Matt Ryan

Posted on

2

Day 34: Consuming a RESTful API with React

A component, users.js:

import React from 'react'

const Users = ({users}) => {
    return (
        <div>
            <center><h1>User List</h1></center>
            {users.map((user) => (
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">{user.name}</h5>
                        <h6 class="card-subtitle mb-2 text-muted">{user.email}</h6>
                        <p class="card-text">{user.company.catchPhrase}</p>
                    </div>
                </div>
            ))}
        </div>
    )
};

export default Users
Enter fullscreen mode Exit fullscreen mode

App.js mounts the user component and makes the API request:

import React, {Component} from 'react';
import Users from './components/users';

class App extends Component {
    render() {
        return (
            <Users users={this.state.users} />
        )
    }

    state = {
        users: []
    };

    componentDidMount() {
        fetch('http://jsonplaceholder.typicode.com/users')
            .then(res => res.json())
            .then((data) => {
                this.setState({ users: data })
            })
            .catch(console.log)
    }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay