Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Ajax (Reactjs + Mobx)

I want to make some fake my ajax calls so when on localhost I can bring back dummy data from a fake method instead of doing real calls to my server(where the structure might not exist).

What is the best way to do this in reactjs + mobx?

I was thinking of making a fake store as this is where all my actions are with my ajax calls but that would involve always making the entire store with all functions.

I then though of maybe extracting out the ajax calls from the store and then mockup those calls but I am not sure the best way to do that.

like image 666
chobo2 Avatar asked Jun 27 '17 17:06

chobo2


1 Answers

Use json-server for faking api calls and redux for state management, I have used this in one of my projects. It is quite simple and requires very less boilerplate code. Redux updates a global store through actions and components can subscribe to store for changes.

See documentation here-

https://github.com/typicode/json-server

http://redux.js.org/

Example from my app- You can make a fake store by creating a db.json and then you can use either default routes provided by json-sever or create your own.

This can be your db.json

{
    "questions": [
        {
            "id": 2,
            "question": "A train running at the speed of 60 km/hr crosses a pole in 9 seconds. What is the length of the train?",
            "options": [
                "120 metres",
                "180 metres",
                "324 metres",
                "150 metres"
            ],
            "answer": 4
        },
        {
            "id": 3,
            "question": "The length of the bridge, which a train 130 metres long and travelling at 45 km/hr can cross in 30 seconds, is",
            "options": [
                "200 m",
                "225 m",
                "245 m",
                "250 m"
            ],
            "answer": 3
        }
    ]
}

start this mock api by running this json-server --watch db.json in your folder with db.json file.

Then use http://localhost:3000/questions

Comment if you want more detailed information on any of stuff mentioned above. I can provide you sample code as I have implemented this full flow.

like image 131
Arshmeet Avatar answered Oct 28 '22 23:10

Arshmeet