Client

Updated: 2020-04-04

Use create-react-app to create a new app

$ npx create-react-app client

You will find a set of files created in the client folder. For now we only care about App.js.

To talk to the server, the best option now is to use the native fetch; and React supports async/await out of the box. The fetch can be called in componentDidMount(), so it would not block the initial rendering, and once the response is available we can update states to let it render again:

async componentDidMount() {
    const response = await fetch("http://localhost:3001/");
    const json = await response.json();
    this.setState({ data: json });
  }

When we render, we need to check if the state is available first:

{
  this.state.data == null
    ? ""
    : this.state.data.rows.map(row => <p>{row.name}</p>);
}

Put them all together.

import "./App.css";

import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
  }

  async componentDidMount() {
    const response = await fetch("http://localhost:3001/");
    const json = await response.json();
    this.setState({ data: json });
  }

  render() {
    return (
      <div className="App">
        <div>
          {this.state.data == null
            ? ""
            : this.state.data.rows.map(row => <p>{row.name}</p>)}
        </div>
      </div>
    );
  }
}
export default App;

CORS: Cross-Origin Resource Sharing

However you may see this error:

Request has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is because the server is running at port 3001, while the client in dev mode is running in 3000.

One solution is to add cors in the server and add app.use(cors()); to your server; or once the client is compiled by npm run build, serve it as part of the server as static files.

Summary

It feels we haven't done much: we simply show the same text in HTML as in our seed data that we fed into the database. However we actually setup the communication channel: from the client to server, and from server to databases. Think about the potentials: we can do all kinds of fancy visualization of the timelines, we can add user interactions, we can dynamically update the underlying datasets. Those would be covered in Part 2.