My First React Application

Overview

Part 1 - Creating the Backend Application

Part 1.1 - Dependency Management & File Infrastructure

Part 1.2 - Modify the package.json file

"scripts" : {
    "start": "node server.js",
    "server": "nodemon server.js"
}

Part 1.3 - Modify the server.js file

const express = require('express');  // import express
const app = express(); // initialize express
const port = 5000; // create port variable to listen on
const funcToRunUponListening = () => console.log(`Server started on port ${port}`);
const funcToRunUponReceivingRequest = (req, res) => {
    const customers = [ // TODO - replace with call to Database
        {"id":1, "firstName":"Ischa","lastName":"Boul"},
        {"id":2, "firstName":"Mark","lastName":"Lauren"},
        {"id":3, "firstName":"Ralph","lastName":""}
    ];    
    res.json(customers);
};

app.get('/api/customers', funcToRunUponReceivingRequest)
app.listen(port, funcToRunUponListening);

Part 1.4 - Running Server and Hitting Endpoint

[{"id":1, "firstName":"Ischa","lastName":"Boul"},
 {"id":2, "firstName":"Mark","lastName":"Lauren"},
 {"id":3, "firstName":"Ralph","lastName":"Jacob"}]







Part 2 - Creating the Frontend Application

Part 2.1 - Install create-react-app cli command

Part 2.2 - Create React application

Part 2.3 - Modify client/package.json to include proxy to backend

"scripts" : {
    ...,
},
"proxy": "http://localhost:5000",

Part 2.4 - Running React Server

Part 3 - Creating Customers components

Part 3.1 - Creating components directory

Part 3.2 - Creating customers directory

Part 3.3 - Creating customers.js

import React, { Component } from 'react';
import './customers.css';

class Customers extends Component {
    constuctor() {
        super();
        this.state = {
            customers:[]
        }
    }    

    componentDidMount() { // runs automatically when component is mounted to the DOM
        fetch('/api/customers') // fetches customers from express server and sets `state`-value to customers that were fetched
            .then(res => res.json())
            .then(customers => this.setState({customers}, () => console.log("Customers fetched...", customers)))
    }

    render() {
        return (
            <div>
                <h2>Customers</h2>
                <ul>{ this.state.customer.map(customer =>
                    <li key={customer.id}>
                        { customer.firstName } {customer.lastName}
                    </li>
                )}</ul>
            </div>
        );
    }
}

export default Customers;

Part 3.4 - Creating customers.css