DEV Community

Cover image for Using Mirage JS to create a fake api with React JS
Leandro RR
Leandro RR

Posted on

Using Mirage JS to create a fake api with React JS

welcome to my first post, today i'm going to show you how to use Mirage JS to make a fake endpoint, after you learn it, i'm sure you will be amazed by it and will use it in your future projects.

What is it?

from Mirage website: Mirage JS is an API mocking library that lets you build, test and share a complete working JavaScript application without having to rely on any backend services.

if you want know more, read the getting started guide.

Before start

install the create-react-app to try Mirage.

$ npx create-react-app testapp
Enter fullscreen mode Exit fullscreen mode

Install Mirage JS

$ npm i --save-dev miragejs
Enter fullscreen mode Exit fullscreen mode

Creating the server

cd to the react folder then create a server.js file inside src/ folder:

$ cd testapp/ ; touch src/server.js
Enter fullscreen mode Exit fullscreen mode

now open the server.js file and type the following code:

import { Server, Model } from "miragejs"

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

    models: {
      user: Model,
    },

    seeds(server) {
      server.create("user", { name: "Bob" })
      server.create("user", { name: "Alice" })
    },

    routes() {
      this.namespace = "api"

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

  return server
}
Enter fullscreen mode Exit fullscreen mode

now import this script inside your src/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {makeServer} from './server';

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

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

serviceWorker.unregister();
Enter fullscreen mode Exit fullscreen mode

Fetch the data

now inside our app.js, use the react functions useState and useEffect to help us with this job:

import { useState, useEffect } from "react"

export default function App() {
  let [users, setUsers] = useState([])

  useEffect(() => {
    fetch("/api/users")
      .then(res => res.json())
      .then(json => {
        setUsers(json.users)
      })
  }, [])

  return (
    <ul data-testid="users">
      {users.map(user => (
        <li key={user.id} data-testid={`user-${user.id}`}>
          {user.name}
        </li>
      ))}
    </ul>
  )
}
Enter fullscreen mode Exit fullscreen mode

now go to the terminal and start the react server:

$ npm run start
Enter fullscreen mode Exit fullscreen mode

now you should be able to see your users being rendered in the view. this is a simple tutorial, feel free to comment if anything is wrong.

Top comments (1)

Collapse
 
benje profile image
Ben Reynhart

Great article thank you!