Data models

date-fns logo

As with the backend it helps to use models representing the data used. These models help the linters ensure that we are using the data correctly and that the correct types are used. We can also use the model to correctly convert to and from the JSON representation used to communicate with the backend API.

As JSON has no date type we use ISO 8601 formatted strings, see the backend validation. To turn these strings into javascript Date instances we'll use date-fns. As it provides all the functionality we'll need using the javascript Date type.

date-fns is installed via npm,

Run this command in frontend/

npm install --save date-fns

We need a model for Todos that can be constructed from a JSON associate array or from user entered form data and then converted back to json when sent to the backend API. The former is achieved by converting the due argument as required into a Date, the latter is achieved via a toJSON method that is automatically called when converting to JSON. The following should be added to frontend/src/models.ts,

import { formatISO, parseISO } from "date-fns";

interface ITodoParams {
  complete: boolean;
  due: Date | string | null;
  id: number;
  task: string;

export class Todo {
  complete: boolean;
  due: Date | null;
  id: number;
  task: string;

  constructor({ complete, due, id, task }: ITodoParams) {
    this.complete = complete;
    if (due instanceof Date) {
      this.due = due;
    } else if (due !== null) {
      this.due = parseISO(due);
    } else {
      this.due = due;
    } = id;
    this.task = task;

  toJSON(): any {
    return {
      complete: this.complete,
        this.due !== null
          ? formatISO(this.due, { representation: "date" })
          : null,
      task: this.task,