0

I am trying to update a value inside of JSON running on a json-server via my React appliction. Each time I make the POST request it replaces all data inside of the JSON instead of updating it. I am not sure what I am missing.

The React App.js:

  //Update JSON
  const updateOptions = async () => { 
    const res = await fetch('http://localhost:5000/options', {
      method: 'POST',
      headers: {
        'Content-type': 'application/json'
      },
      body: JSON.stringify({score: 10})
    })
  }

When this function is called, it adds score: 10 to the JSON but removes everything else.

JSON Before:

{ "options": 
  {
    "gametype": "rand",
    "gamecat": 11,
    "score": 0
  }
}

JSON After:

{
  "options": {
    "score": 10
  }
}

I'm not sure why it's removing all other data from the JSON, what am I missing?

Vega
  • 27,856
  • 27
  • 95
  • 103
Barkley101
  • 65
  • 1
  • 1
  • 7
  • Short answer appears to be that your API (at `localhost:5000`) is treating the `POST` verb as a full update (more akin to what `PUT` normally does) as opposed to a partial update - https://restfulapi.net/rest-put-vs-post/ – msbit Nov 02 '21 at 04:37
  • for update the JSON, I think you should use PUT instead of POST – barzin.A Nov 02 '21 at 04:37
  • 1
    Can you show us the code that is running on your json-server for the /options route? – Jason Nov 02 '21 at 04:44
  • @barzin.A Using PUT instead of POST makes no change and has the same effect. – Barkley101 Nov 02 '21 at 05:21
  • 1
    @Jason There is no code to speak of for json-server, it's an npm package that allows you to run a server locally. It is running in a 'watch' state. There is only a JSON file that contains the above JSON. – Barkley101 Nov 02 '21 at 05:23
  • 1
    You want to use `PATCH`. See https://github.com/typicode/json-server#singular-routes – Phil Nov 02 '21 at 05:49
  • 1
    You should set an ID: 1 for options and call http://localhost:5000/options/1 with PUT HTTP verb – barzin.A Nov 02 '21 at 05:57
  • 1
    @barzin.A there's absolutely nothing wrong with using singular routes. See the link above – Phil Nov 02 '21 at 20:29

0 Answers0