Search code examples
javascriptfetchresponsehttp-status-codes

Is there a less hard-coded alternative to using if (response.status === 201)?


I am using the Fetch API to retrieve some external data for my application. Here is my code:

  fetch("http://127.0.0.1:8000/dictionary/define", {
    method: "POST",
    body: JSON.stringify(values),
  })
    .then(response => {
      if (response.status === 201) router.push("/");
    })
    .catch(error => alert(error));

I was wondering whether there was a cleaner/less hard-coded alternative to my if (response.status === 201) condition to indicate that everything went well?


Solution

  • I would consider this code perfectly fine. You're looking for a 201 response so you do just that.

    If you're only looking for a successful response just use response.ok.

    The only cleanup I would consider to your existing code is storing all of your response status codes in a constant so it can be more human readable.

    Something like this:

    export const HttpStatusCodes = Object.freeze({
      Created: 201,
    });
    

    Then you could do response.status === HttpStatusCodes.Created) instead, which to me is much easier on the eyes.