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
Install Mirage JS
$ npm i --save-dev miragejs
Creating the server
cd to the react folder then create a server.js
file inside src/
folder:
$ cd testapp/ ; touch src/server.js
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
}
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();
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>
)
}
now go to the terminal and start the react server:
$ npm run start
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)
Great article thank you!