API integration in React Part 2.

0

Hello Guys, We saw about Simple API Integration in the last blog. And we also had a show to API's response.

Now, this blog is going to be even more interesting, in which we will see about some advanced API integration in React. And we will learn about some more methods. And for this, we will test on local node API. Because we cannot use all these methods in the API last time we did it.

In this blog, we will create a form and we will send the data of that form to the API so It will create an entry for that data in our database. And after that, we will also edit that data and then also use the delete method

There are mainly four types of methods in API

Get Method As you have seen in my last blog. I have used the Get method, we used it to get data.

Post MethodWe use the Post method to send data to API. It's used to create an entry.

Put MethodWe use the PUT method to update API data. But many people do not use this too much instead, they use the Post method.

Delete MethodWe use the Delete method to delete API's data.

How to use Post Method in React API Integration?

We will first use the post method. Inside that, we will send JSON data to the API. For that, we have to create a form in React Application and send the data of that form to the API. I have made a #form Validation in the previous blog. I will modify that form to send the data to the API.

We have made a form as shown below with input name, email, password, confirm, password, and phone number. We will send this form's data to the API and after that API will take our request and it will process. And after that, we will show API's response.

I am currently showing how to send form data with React Formik to API. For that, we will create one more function in the apiConnection's folder and users.js file.

userRegister function code

export const userRegister = (first_name, last_name, phone, email, password, confirm_password, callback) => {
    let headers = new Headers();
    headers.append('Content-type', 'application/json');
    headers.append('accept', 'application/json');
     fetch(serverApiBaseUrl+'auth/signup',
     {
         method: 'POST',
         headers,
         body:JSON.stringify({
            first_name,
            last_name,
            phone,
            email,
            password,
            confirm_password
            })
     })
     .then((response) =>callback(response))
     .catch((error)=>{console.log(error)})
}

After that, we will call the userRegister function when the user submits the form. And Inside that function, we will pass all the input's values.

while on form submit we have called the userRegister function as you can see. From this, we will pass form data to the userRegister function and the userRegister function will call the API.

After that, we have created a callback file as we always do. Where we get the API's response.

This is our Registration Form code

import React from 'react'

import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { userRegister } from '../apiConnection/Users';

export default function FormikValidation() {

    const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/

    const LoginSchema = Yup.object().shape({
        first_name: Yup.string()
            .required("Your First Name is required"),
        last_name: Yup.string()
            .required("Your Last Name is required"),
        email: Yup.string()
          .email("Invalid email address format")
          .required("Email is required"),
        password: Yup.string()
          .min(8, "Password must be 8 characters at minimum")
          .required("Password is required"),
        cPassword: Yup.string()
        .required('Confirm Password is required')
        .oneOf([Yup.ref('password'), null], 'Passwords must match'),
        phone: Yup.string()
        .required("Phone Number is required")
        .matches(phoneRegExp, 'Phone Number is not valid')
        .min(10, "Phone Number must have 10 digits")
        .max(10, "Phone Number must have 10 digits"),
      });


    const registerCallback=(response => {
        if(response.status === 200){
			response.json().then(data => {
				console.log('getting response from api', data)
			})
		}
    })


    return (
        <>
            

            <div className="container">
                <h3 className="my-4 text-center">Registration Form</h3>
                <div className="row">
                    <div className="col-lg-6 offset-lg-3">

                    <Formik

                        initialValues={{ 
                            email: "", 
                            password: "" 
                        }}
                        validationSchema={LoginSchema}
                        onSubmit={(values) => {
                            console.log(values);
                            userRegister(values.first_name, values.last_name, values.phone, values.email, values.password, values.confirm_password, registerCallback)
                        }}
                        >
                        {(props) => (
                            <Form>

                                <div className="form-group">
                                    <label htmlFor="Name">First Name</label>
                                    <Field type="text" 
                                        name="first_name"
                                        className={`form-control ${props.touched.first_name && props.errors.first_name ? "is-invalid" : ""} `}
                                        placeholder="Enter Your First Name"
                                        autocomplete="off"/>

                                    <ErrorMessage
                                        component="div"
                                        name="first_name"
                                        className="invalid-feedback"
                                        />
                                </div>

                                <div className="form-group">
                                    <label htmlFor="Name">Last Name</label>
                                    <Field type="text" 
                                        name="last_name"
                                        className={`form-control ${props.touched.last_name && props.errors.last_name ? "is-invalid" : ""} `}
                                        placeholder="Enter Your Last Name"
                                        autocomplete="off"/>

                                    <ErrorMessage
                                        component="div"
                                        name="last_name"
                                        className="invalid-feedback"
                                        />
                                </div>

                                <div className="form-group">
                                    <label htmlFor="Email ID">Email</label>
                                    <Field type="email" 
                                        name="email"
                                        className={`form-control ${props.touched.email && props.errors.email ? "is-invalid" : ""} `}
                                        placeholder="Enter your Email"
                                        autocomplete="off"/>

                                    <ErrorMessage
                                        component="div"
                                        name="email"
                                        className="invalid-feedback"
                                        />
                                </div>

                                <div className="form-group">
                                    <label htmlFor="Password">Password</label>
                                    <Field 
                                        name="password" 
                                        type="password"
                                        className={`form-control ${props.touched.password && props.errors.password ? "is-invalid" : ""} `} 
                                        placeholder="Enter Password"/>

                                    <ErrorMessage
                                        component="div"
                                        name="password"
                                        className="invalid-feedback"
                                        />
                                </div>

                                <div className="form-group">
                                    <label htmlFor="Password">Confirm Password</label>
                                    <Field 
                                        name="cPassword" 
                                        type="password" 
                                        className={`form-control ${props.touched.cPassword && props.errors.cPassword ? "is-invalid" : ""} `} 
                                        placeholder="Enter Password"/>

                                    <ErrorMessage
                                        component="div"
                                        name="cPassword"
                                        className="invalid-feedback"
                                        />
                                </div>

                                <div className="form-group">
                                    <label htmlFor="Password">Phone Number</label>
                                    <Field 
                                        name="phone" 
                                        type="text" 
                                        className={`form-control ${props.touched.phone && props.errors.phone ? "is-invalid" : ""} `} 
                                        placeholder="Enter Phone Number"
                                        autocomplete="off"
                                        />

                                    <ErrorMessage
                                        component="div"
                                        name="phone"
                                        className="invalid-feedback"
                                        />
                                </div>

                                <div className="my-3 text-center">
                                    <button type="submit" className="btn btn-primary btn-block py-2"> Register Account</button>
                                </div> 
                    
                            </Form> 
                        )}
                    </Formik>

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

Currently, I have a console log the API's response. In the upcoming blog, We will show the response's message in a pretty good way.

Now we can see the console log on the successful response of the API. In further, I will also show you guys how to create an API in Node currently you can just understand that we send data to the API and we get the response from that.

How to use Put Method in React API Integration?

Now we will learn about the Put method. Inside it, we will update the user's data through the API. As I mentioned, we can also use the Post method instead of the Put method. It's all depends on the API's method.

For sending the data in the Put method we need to also send data to the API. Inside my API when the user register. I have made status pending which is the default value from the API. Now we will make the user's status Active from the Put method function. For that, we will create a form with an email address only in which we will fill email address whose status needs to be changed.

export const userUpdateStatus = (id, status, callback) => {
    let headers = new Headers();
    headers.append('Content-type', 'application/json');
    headers.append('accept', 'application/json');
     fetch(serverApiBaseUrl+'auth/update-status',
     {
         method: 'PUT',
         headers,
         body:JSON.stringify({
            id,
            status
            })
     })
     .then((response) =>callback(response))
     .catch((error)=>{console.log(error)})
}

How to use Delete Method in React API Integration?

The delete method is almost like this, which helps us to send a delete request to the API. Inside it, we pass the Id or the parameter to the API. And We write the Delete method function as written in the below.

export const deleteQuery=(id, callback)=>{
    let headers = new Headers();
    headers.append('Content-Type', 'application/json'); 
    headers.append('Access-Control-Allow-Origin', serverApiUrl);
    headers.append('Access-Control-Allow-Credentials', 'true');
    headers.append('GET', 'POST', 'OPTIONS'); 

    fetch(serverApiBaseUrl+'auth/deleteUser/',
    {
        method: 'DELETE',  
        headers,
        body:JSON.stringify({id})
        
    })
    .then((response)=>callback(response)) 
    .catch((error)=>{console.log(error)})  
}

How to use formData in React API Integration?

But sometimes we have to use the FormData function, for that we cannot use application/json in the header. It happens when we have to send a media file to the server. And some times it is written in the code of the API for accepting FormData requests.

    export const UploadUserPic=(pic, userId, callback, errorCallback) => {
        let formData = new FormData();
        formData.append('userId', userId)
        formData.append('pic', pic);
        fetch(serverApiBaseUrl+'api/auth/upload-user-pic',{
            method: 'POST',
            body: formData
        })
        .then((response) => callback(response))
        .catch((error)=>{
            console.log(error)
            errorCallback(error)
        })
    }

These were some of the common ways which help us API integration in React Application using fetch function.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !