How to Write a POST Request Using Fetch API in React

Irakli Tchigladze Feb 02, 2024
  1. Write a POST Request Using Fetch API in React
  2. POST Request Using Fetch With Set HTTP Headers
  3. POST Request Using Fetch With async/await in React
  4. POST Request Using Fetch With Error Handling
How to Write a POST Request Using Fetch API in React

Sending and receiving data via API is an essential feature of any complex web application.

React is a very popular framework for building web apps. Like other JavaScript-based frameworks, it allows developers to use Fetch API to communicate with servers.

This guide will show how to write a POST request in React.

Write a POST Request Using Fetch API in React

When building a React class component, you must make an HTTP request in lifecycle methods. Usually in the componentDidMount() method.

There is a useEffect() hook for functional class components, which substitutes lifecycle methods.

The structure of a Fetch request looks like fetch(endpointURL, requestOptions).

To better understand, let’s look at an actual functional component in React.

export default function App() {
  const url = "www.somewebsite.com";
  const options = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "Irakli Tchigladze" })
  };
  useEffect(() => {
    fetch(url, options);
  }, []);
  return <div className="App"></div>;
}

Live demo on CodeSandbox.

In this example, we make a request using the useEffect() hook. The first argument to the hook is a callback function, where we use the fetch method to make the request.

The url variable contains the URL of the API endpoint where we want to POST data.

The options variable contains an options object, which is an essential component for making a POST request. It has three properties: method, headers, body.

The value of the method property specifies the type of action that needs to be performed. In this case, that is 'POST', which tells the server to create a new record.

It can also have these values: 'GET', 'PUT', 'PATCH', 'DELETE'.

The headers property is used to specify how the data should be handled.

Finally, the body property contains the data which needs to be transferred to the server on the other side of the API endpoint.

POST Request Using Fetch With Set HTTP Headers

As we already said, the headers property refers to the purpose of data and how the receiving application should handle it.

In our example, we set the value of 'application-json', which specifies that the data should be parsed as JSON.

POST Request Using Fetch With async/await in React

Instead of using the then() method to chain promises, many developers use cleaner async/await syntax. Let’s take a look at the example.

export default function App() {
  const url = "www.somewebsite.com";
  const options = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "Irakli Tchigladze" })
  };
  useEffect(() => {
    const getData = async () => {
       try {
        const response = await fetch(url, options);
        const data = await response.json();
        return data;
    } catch (e) {
        return e;
    }
    }
    getData()
  }, []);
  return <div className="App"></div>;
}

In this example, we have the same url and options, but we replace then() and chained promises with async and await keywords.

To replace promise chains with the await keyword, we need to use the keyword async in the function definition.

Note that we cannot use the async keyword directly with the callback function, which is the first argument to the useEffect() hook. Instead, we define a new function, getData, within the callback and call it at the end of the function.

POST Request Using Fetch With Error Handling

Many developers make a common mistake when trying to make a POST request. The mistake is to provide the wrong value for the body parameter in the options object.

The body parameter takes a JavaScript object with key-value pairs of its own. Often developers get an error because they are passing a raw JavaScript object.

If you’re in a similar situation and keep getting an error, try to pass raw data as the argument to the JSON.stringify() method.

The easiest way to implement error handling when making a POST request is to use the try...catch statement. Let’s look at the getData function from the example above.

const getData = async () => {
       try {
        const response = await fetch(url, options);
        const data = await response.json();
        return data;
    } catch (error) {
        return error;
    }

The function body contains two code blocks - one under the try statement and the other under catch.

First, we try to make the request and return data. If for some reason, there is an error and the request is unsuccessful, JavaScript will execute the code in the catch block.

The catch statement takes one argument, a variable name that stands for what caused the request to fail. We can return this value and examine what went wrong.

Many developers log this variable to the console.

Irakli Tchigladze avatar Irakli Tchigladze avatar

Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.

LinkedIn