0

I have a simple counter app that hits an API. When a user hits + button, it should make a PUT request to update the API. Question is, is it best practice to always pass a body in to update it. Or is it okay to just have an empty PUT request with logic?

/counter.js : empty body; just sending an PUT request:

const handleAdd = () => {
    try {
        const response = await fetch(`/api/counter`, {
          method: "PUT",
          headers: {
            "Content-Type": "application/json"
          },
        });
        const counter = await response.json();
        return counter;
      } catch (err) {
        return null;
      }
  };
return (
<button onClick={() => handleAdd()}> + </button>
)

/pages/api/counter.js

export default async function handler (req, res) {
    add + 1
    return res
}

Or should I have a generic update in counter.js and add body into the counter.js file?

export default async function handler (req, res) {
    const newCounter = res
    return res
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Omilight
  • 7
  • 4
  • It's not clear what you're doing in the last part of your question. But in general, PUT requests should be idempotent — making the same request multiple times shouldn't change the result. So you'd want to send the new counter value as part of the body. If you want the server to decide on the new counter value, a POST would be more appropriate. – JW. Jun 30 '23 at 16:54
  • @JW. So my body should never be: count: count + 1. It should somehow already hold a variable that holds a value: "3", and i would do count: 3? Or how else would i do it? – Omilight Jul 03 '23 at 16:10
  • Yeah. I'd just switch it to POST, if you want to be more correct. You don't need a body. – JW. Jul 03 '23 at 16:17

0 Answers0