Logo

Github

LinkedIn

Home

January 29, 2020

3 min read

Using Mirage.js to jumpstart your frontend development

In this article, we'll learn about how to build a front-end application without back-end APIs using Mirage.

Table of Contents

Getting started with Mirage

Let's create a new application from scratch:

mkdir mirage-mock-api && cd mirage-mock-api

Now, let's install Mirage in our application:

yarn add --dev miragejs

Next, we'll create a route to get a list of dog breeds. Let's create a new file called server.js inside src directory:

src/server.js

const Mirage = require("miragejs");

function makeServer({ environment = "development" } = {}) {
  let server = new Mirage.Server({
    environment,

    models: {
      dog: Mirage.Model,
    },

    seeds(server) {
      server.create("dog", { name: "Labrador Retrievers" });
      server.create("dog", { name: "German Shepherds" });
    },

    routes() {
      this.namespace = "api";

      this.get("/dogs", (schema) => {
        return schema.dogs.all();
      });
    },
  });

  return server;
}

module.exports = {
  makeServer,
};

Adding Mirage to our front-end application

Let's create a React application using Create React App:

npx create-react-app mirage-react-app && cd mirage-react-app

Now, let's import the Mirage app that we just created:

src/index.js

import React from "react";
import ReactDOM from "react-dom";
import { makeServer } from "mirage-mock-api/src/server";

import App from "./App";

if (process.env.NODE_ENV === "development") {
  makeServer();
}

ReactDOM.render(<App />, document.getElementById("root"));

Also, let's test our Mirage API:

src/App.js

import React, { useState, useEffect } from "react";

export default function App() {
  let [dogs, setDogs] = useState([]);

  useEffect(() => {
    fetch("/api/dogs")
      .then((res) => res.json())
      .then((json) => {
        setDogs(json.dogs);
      });
  }, []);

  return (
    <ul data-testid="dogs">
      {dogs.map((dog) => (
        <li key={dog.id} data-testid={`dog-${dog.id}`}>
          {dog.name}
        </li>
      ))}
    </ul>
  );
}

Now, if we visit http://localhost:3000, we'll see the Mirage API:

Mirage API

Features of Mirage

  1. Database
  2. Models
  3. Relationships
  4. Factories
  5. Fixtures
  6. Serializers

References

The front-end application is available here and the back-end application is available here.

Conclusion

In this article, we've learnt about Mirage and how it can help us develop front-end applications even when the back-end part isn't ready! I hope that this article helps you in your future projects.