My JSON Server from Typicode updating database in ReactJS

1.6k views Asked by At

I've been recently trying to work with a fake API using my json server from typicode. Using fake APIs is pretty new to me so my question might soung a little odd.

Am I understanding the concept of this fake API server right, that I can update the database with a post request in ReactJS? Or does the database never change through post request and I do only get a result in my console log?

In particular I am trying to post form data from a form to the my json server through a post request.

Thanks so far!

The code I use to post data:

axios.post(`my-url`, { user })
                    .then(res => {
                      console.log(res);
                      console.log(res.data);
                    })
                        }
2

There are 2 answers

7
devserkan On BEST ANSWER

I assume that you are using json-server package and using the server like that. In this case, the successful POST requests you make will be persisted in the file you provided to the server or the default one if you don't provide any specific file.

If you want to use json-server and make the changes persisted, you can use its npm package:

npm install -g json-server

Then, create a db.json file in your project directory and provide the data structure you want to use:

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ]
}

If you don't provide a db.json file it creates automatically when you start the server. So, it is up to you.

Then, you should start the server:

json-server db.json

The server will be on port 3000, if there is another app running on this port, you can specify the port when starting it:

json-server db.json -p 3001

Now, you can make requests to http://localhost:3001/posts. Just check its documentation about the requests.

0
toeyeen On

You can't make a post request to this server https://my-json-server.typicode.com/${github-username}/${github-repo}/${event},

As of the time of this response, you can only make a get request, I advise you to use JSON-server on your local machine.

Create a db.json file on the project folder,

Example add something like this to the file

{
  "events": [
    {
      "id": 123,
      "category": "animal welfare",
      "date": "January 28, 2022",
      "time": "12:00",
    },
    {
      "id": 456,
      "category": "nature",
      "date": "January 30, 2022",
      "time": "11:00",
    },
}

run npm install -g json-server and json-server --watch db.json to provide the baseUrl that will be needed to make your requests