How do I get the HTTP response code from a successful React query?
When developing with React, retrieving HTTP response codes often depends on the data-fetching library you choose. For instance, if you're using the Fetch API or third-party libraries like Axios, the approach varies slightly. Below, I'll explain how to retrieve HTTP response codes in both scenarios.Using Fetch APIWhen using the native Fetch API for data requests, you can retrieve HTTP response codes by checking the property of the response object. Here's a simple example:In this example, will yield values such as , , or . is a boolean that evaluates to when the status code falls within the 200–299 range, allowing you to verify if the request was successful.Using AxiosIf you're using Axios for HTTP requests, retrieving response codes is straightforward. Axios requests return a response object containing a field. Here's an example:With Axios, if the request is successful (i.e., HTTP status code in the 200–299 range), you can directly access the status code from . If the request fails (e.g., status code is 400 or 500), the error object contains the HTTP status code.SummaryWhether using Fetch or Axios, retrieving HTTP response codes is relatively straightforward, as it involves accessing the property of the response object. By doing so, you can handle various HTTP statuses, such as redirects, client errors, or server errors, and implement corresponding logic. This is crucial for developing robust web applications.