DEV Community

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

Posted on

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)