-1

So, I have a button that posts an object with "id", "name", "description" properties to the api. What I want to achieve is to prevent posting any other object if they have the same "id" of the object posted before. Is that even possible?

develop05
  • 487
  • 1
  • 9
  • 23
  • You would have to do a GET to the API to make sure the `object.id` you are sending isn't already there. What kind of API is it? – Karl Taylor Sep 20 '18 at 13:36
  • Or you can reply to the POST call with `409 Conflict` as suggested in https://stackoverflow.com/questions/3825990/http-response-code-for-post-when-resource-already-exists. – Petr Broz Sep 20 '18 at 13:38
  • I'm just testing this on a fake json-server – develop05 Sep 20 '18 at 13:38

2 Answers2

0

I would suggest that the server needs to check if the ID already exists and if so return you a proper HTTP error-code you handle in your client-side fetch code.

In addition you can keep track of what you already sent to the server (for this workstation only) by storing the already sent Ids vor example in the local state, a Redux state or in another global object. You can also use IoC container like Inversify to hold a singelton at hand which can do the bookkeeping of already sent IDs. There are many options. Let us know if you have any more specific requirement or library already in use.

Marc
  • 4,715
  • 3
  • 27
  • 34
0

If you have control over your API you can reject any POST requests with the same id.

If you do not have control over the API then you have to handle that check explicitly yourself. For example you could store it in a Set and before doing the fetch call you can check if it already exists.

If what you are asking is if there is a pre-defined way to do this via fetch, then no there is not.

ᴘᴀɴᴀʏɪᴏᴛɪs
  • 7,169
  • 9
  • 50
  • 81