How to send data to API into reactJS

In this article, we will learn how to send data to an API in reactJS. Let’s create a reactJS application that will get the data from the user and send the data to API to store it in the database.

There are five basic HTTP methods that we have to be familiar with.

  • GET: Used to get (fetch) data from an API.
  • POST: To add some data to a database through the API.
  • PUT: With this, existing data can be modified or can be inserted into a new one.
  • PATCH: The PATCH method helps to update existing data.
  • DELETE: This method helps to delete data from the database.

With the help of these HTTP methods, any kind of data can be added, modified, and deleted. To learn about fetching the data from an API in reactJS, Read This Article.

Steps to send data to the database through an API using the HTTP method (POST) in reactJS.
  • Setup the environment (create a component, import component, etc.)
  • Get data (we will be using the form to get the form data)
  • Send to the API (HTTP POST method)

Setup the environment

  • Create a functional component

import React from 'react';

const ReactForm = () => {
    return (
        <div>

        </div>
    );
};

export default ReactForm;
  • Import this component into App.js file
import ReactForm from "./components/ReactForm";
import React, { useState, useEffect } from "react";

import ReactForm from "./components/ReactForm";


const App = () => {

  return (
    <div >
      <ReactForm />
    </div>
  );
}

export default App

Get the Data from the user in ReactJS

We will be using form data to send to the Database through API. For that, we will use react-hook-form npm package.

  • Write the below code into the functional component,
import React from 'react';
import { useForm } from "react-hook-form";
const ReactForm = () => {

    const { register, handleSubmit } = useForm();

    const onSubmit = data => {
        // console.log the data to see the input values
        console.log(data)
    };
    return (
        <div className=" flex justify-center lg:h-screen items-center">
            <div className="card w-full md:w-96 items-center shadow-2xl bg-base-100">
                <form onSubmit={handleSubmit(onSubmit)} className="card-body w-full lg:w-96">
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Name</span>
                        </label>
                        <input
                            {...register("name", { required: true })}
                            type="text" placeholder="name" className="input input-bordered" />

                    </div>

                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Email</span>
                        </label>
                        <input
                            {...register("email", { required: true })}
                            type="email" placeholder="email" className="input input-bordered" />

                    </div>
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Address</span>
                        </label>
                        <input
                            {...register("address", { required: true })}
                            type="text" placeholder="address" className="input input-bordered" />



                    </div>
                    <div className="form-control mt-6">
                        <button type="submit" className="btn btn-primary">Send Data</button>
                    </div>

                </form>

            </div>
        </div>
    );
};

export default ReactForm;

After console.log, the result can be seen in the browser dev tool.

Note: We are using Tailwind CSS and Daisy UI to style the component. And to know more about “Getting the form data”, Read This Article.

Send Data To API in ReactJS

  • Store the input data into an object
    const { register, handleSubmit } = useForm();
    const onSubmit = data => {
        // console.log the data to see the input values
        console.log(data)
// storing input data into userData objeect
        const userData = {
            name: data.name,
            email: data.email,
            address: data.address
        }    
    };
  • Write an HTTP fetch (POST method) inside the onSubmit() function.
 const onSubmit = data => {
        // console.log the data to see the input values
        console.log(data)
        fetch('',{
            method:"POST",
            headers:{
                'content-type':"application/json"
            },         
        })
    };
  • Pass the stored form data object into the body of this POST method,
const onSubmit = data => {
     // console.log the data to see the input values
     console.log(data)
     const userData = {
         name: data.name,
         email: data.email,
         address: data.address
     }
     fetch('', {
         method: "POST",
         headers: {
             'content-type': "application/json"
         },
         body: JSON.stringify(userData)
     })
         .then(res => res.json())
         .then(data => {
             console.log(data)
         })
 };

That’s it…that’s pretty much it. Just add an API inside the fetch('') in where the data is supposed to be stored.

import React, { useEffect } from 'react';
import { useForm } from "react-hook-form";
const ReactForm = () => {

    const { register, handleSubmit } = useForm();

    const onSubmit = data => {
        // console.log the data to see the input values
        console.log(data)
        const userData = {
            name: data.name,
            email: data.email,
            address: data.address
        }
        fetch('', {
            method: "POST",
            headers: {
                'content-type': "application/json"
            },
            body: JSON.stringify(userData)
        })
            .then(res => res.json())
            .then(data => {
                console.log(data)
            })
    };
    return (
        <div className=" flex justify-center lg:h-screen items-center">
            <div className="card w-full md:w-96 items-center shadow-2xl bg-base-100">
                <form onSubmit={handleSubmit(onSubmit)} className="card-body w-full lg:w-96">
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Name</span>
                        </label>
                        <input
                            {...register("name", { required: true })}
                            type="text" placeholder="name" className="input input-bordered" />

                    </div>

                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Email</span>
                        </label>
                        <input
                            {...register("email", { required: true })}
                            type="email" placeholder="email" className="input input-bordered" />

                    </div>
                    <div className="form-control">
                        <label className="label">
                            <span className="label-text">Address</span>
                        </label>
                        <input
                            {...register("address", { required: true })}
                            type="text" placeholder="address" className="input input-bordered" />



                    </div>
                    <div className="form-control mt-6">
                        <button type="submit" className="btn btn-primary">Send Data</button>
                    </div>

                </form>

            </div>
        </div>
    );
};

export default ReactForm;

This is how we can send data to an API to store in a database.