[Node.js] Mock an API for Local Development in React with Mirage JS

元气小坏坏 提交于 2020-08-19 20:51:28

Mirage JS lets you mock out production APIs directly alongside your frontend React code. You can tweak the data or force a network request to hang, so you can quickly design different states of your application. In this way Mirage lets you build every state of your UI regardless of the state of your production API.

Check out Mirage's React quickstart here.

 

// src/App.js
import React, { useState, useEffect } from "react"
import { Server } from "miragejs"

let server = new Server()
server.get("/api/users", { users: [{ id: 1, name: "Bob" }] })

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

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

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  )
}

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!