E
E
Ezrayter2019-11-29 20:16:46
React
Ezrayter, 2019-11-29 20:16:46

What is React Mock API? And how to use it?

Good day!
There is a react application with axios requests to the server. Sometimes it happens that the server stops working. I was told to 'mock' api methods on the client in order to be able to work without a server.
What does it mean? Do I understand correctly that you can add code that will intercept api requests and return the data that I specify? As I understand it, this is used for testing (testing articles are issued on the Internet for the request "react mock api"). Is it possible to apply this not for testing, but for working without an active server?
I would be grateful for explanations and links to resources where you can read about all this.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Robur, 2019-11-29
@Robur

What is React Mock API?

there is no such API. React generally doesn’t care whether you go to the server or take data from somewhere else.
You can block requests in the application to work without a server, since you have axios, then see how best to do it for him.
here is the first thing that came across: https://github.com/ctimmerm/axios-mock-adapter

D
Dmitry, 2019-11-29
@dimoff66

A request to the server api is asynchronous functions that send a request and wait for a response, respectively, you can replace them with your own, for example, you have an object with server request functions

const serverAPI = {
  getCategories: () => fetch('/categories'),
  getCategory: (id) => fetch('/categories/' + id)
}

And there are mock requests with the same keys as serverAPI
// Создадим базу данных
const mockDB = {
  categories: [
    { id: 1, name: 'products'}, 
    { id: 2, name: 'services'}
  ]
}

const mockAPI = {
  getCategories: () => Promise.resolve(mockDB.categories),
  getCategory:  (id) => Promise.resolve(mockDB.categories.find(v => v.id === id)),
}

And create an object , make
all requests from the code to currentAPI, you can switch it from mock to normal and vice versa
Object.assign(currentAPI, mockAPI)
Object.assign(currentAPI, serverAPI)

Mock DB data can be stored in localStorage between sessions. Of course this will only work locally.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question