Send data from your react application to the backend using FETCH

Send data from your react application to the backend using FETCH

ยท

3 min read

One of the perks of building a react application includes the ability to scale it up, and make it a full-fledged application that interacts with another program using an API.

So you've built a functional react application, and now comes the time for you to interact with a backend API.

API, Application Programming Interface

An API is a way for two or more computer programs to communicate with each other.

You have built a form in your react application that works perfectly.

And you have built a server that accepts data in a form, which you have tested in the postman and works fine.

The way in which these two independent applications communicate with each other is through an API.

Fetch() API

The Fetch API is a modern interface that allows you to make HTTP requests from web browsers (e.g your react applications) to servers.

HTTP requests

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. An HTTP request is made from a client to a host located on the server, and it is used to structure requests and responses over the internet.

HTTP has methods, a verb (like GET, PUT or POST ) or a noun (like HEAD or OPTIONS ), that describes the action to be performed.

Therefore in order to send data from our react applications to the server, we use the fetch API, which is inbuilt into javascript to make HTTP requests to our server.

 return (
    <div>
      <form className="create-note">

         <input
          value={note.title}
          onChange={addNote}
          name="title"
          placeholder="Title"
        />
        <textarea
          onClick={expandTabs}
          value={note.content}
          onChange={addNote}
          name="content"
          placeholder="Take a note..."
          rows={state ? "3" : "1"}
        />
          <IconButton onClick={submitNote}><AddIcon /></IconButton>
      </form>
    </div>
  );

In the above code, we have a simple form which takes in two inputs - title and content, and when we click on the submit button, we want to send it to a server

function submitNote(e){    
      fetch('http://localhost:8000/api/v1/notes', {
            method: 'POST',
            mode: 'cors',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(note)
        })
            .then((response) => {
                console.log(response);
            })
            .catch((err) => {
                console.log(err.response.data);
            });
   }

Let's break down what's going on here:

The fetch operation is triggered when we submit the form. The API URL is passed to the fetch function so that the client knows the address to send the data.

method: 'POST' This is the HTTP method to be performed on the API Url. We want to send information that is specified inside the function

mode: cors (Cross-Origin Resource Sharing (CORS)) is an HTTP-header-based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

headers: {'Content-Type': 'application/json'} The header is a field in the HTTP request or response that passes additional context and metadata about the request or response. In this case, we indicate that the request body format is JSON.

body: JSON.stringify(note) The body is the request that our API expects and JSON.stringify(note) ensures that our data object is converted to JSON.

Possible Errors You might encounter:

  1. POST http://localhost:8080/api/v1/notesnet::ERR_CONNECTION_REFUSED - Your server is probably not being run or the URL is wrong

  2. POST http://localhost:8000/api/v1/notes 500 (Internal Server Error) - If your server works but the client returns this error, ensure that you have cors enabled and headers in your fetch request

             mode: 'cors',
                 headers: { 'Content-Type': 'application/json' },
    
    1. Ensure that you log the error.response.data in your fetch request to get more information about the error, you might be having.

      Happy coding ๐Ÿต

Additional Resource:

  1. Proxying API Requests in development

  2. How to use POST requests in React