How to create common helper class in React JS

[Simple Way]-How to create common helper class in React JS? | Fetch data from API using helper class and functions

Recently I’m working on a react js project in which we need to create a helper class for our application.There is a lot of similar question to creating a file with multiple functions. So i decided to write article on this topic and share the code so that other developers can take help from this post.

we want to create a js file with  reusable functions and then we will import that into components and call it.We want to create a class that will work as a global helper class for our application and we will use that helper in another class or component.

For example, we want to perform the insert, update and delete operation using the rest API.For that,we created a httphelper for our application using that helper we will make the different HTTP requests to rest API.

Create helper class in react js Example

I have created a common function for making HTTP post, put, delete and get requests. Now you can use that function in any component.As you can see in the below example I have created a common helper class in React JS using ES6 which is used by another component in our application.

I have created the helper restHelper.js, we will use helper restHelper.js to make the different HTTP requests i.e GET, POST, PUT, DELETE. The concept is to have a helper class that allows us to facilitate the HTTP requests from react components.

Fetch data from API using helper class and functions

You can use the below helper in any of your react applications with any js framework like angular or Vue.js.

The callAPI() function is an asynchronous function that takes endpointurl as parameters to make the HTTP request and an options object. If the options parameter, is not supplied i.e if options will be an empty object, then we assign the default values as the defaultHTTPMethod and defaultHTTPHeaders Otherwise, we replace the obtained values with the default values.

we also have another function called AbortController that will allow us to abort the HTTP request after a certain time if the API server does not return a response.

restHelper.js

export const restHelper = () => {
    
    const callAPI = async (endpointurl, options = {}) => {
        const defaultHTTPMethod = "GET"
        const defaultHTTPHeaders = {  //set defaultHeaders of Http request
            "Content-Type": "application/json",
            Accept: "application/json",
        }
        const controller = new AbortController() //using  AbortController to cancel ongoing fetch requests
        options.signal = controller.signal

        options.method = options.method || defaultHTTPMethod

        options.headers = options.headers
            ? { ...defaultHTTPHeaders, ...options.headers }
            : defaultHTTPHeaders

        options.body = JSON.stringify(options.body) || false
        if (!options.body) delete options.body

        setTimeout(() => { // cancel request if it will take more then 5s 
            controller.abort()
        }, 5000)

        try {
            const apiResponse = await fetch(endpointurl, options)
            debugger;
            return await apiResponse.json()
        } catch (err) {
            return err
        }
    }

    //calling get API For fetching data
    const get = (endpointurl, options = {}) => callAPI(endpointurl, options)

    //Post to insert 
    const postCreate = (endpointurl, options) => {
        options.method = "POST"
        return callAPI(endpointurl, options)
    }


    //Put Api calling
    const putUpdate = (endpointurl, options) => {
        options.method = "PUT"
        return callAPI(endpointurl, options)
    }

    //Delete Api calling
    const deletedata = (endpointurl, options) => {
        options.method = "DELETE"
        return callAPI(endpointurl, options)
    }

    return {
        get,
        postCreate,
        putUpdate,
        deletedata,
    }
}

Import helper class in component

import React, { useState, useEffect } from "react"
import {HttpHelper} from "./path/to/restHelper.js"

have a look at the below Crudtourists.js component , here I have imported the helper and using function.

Finally, we export the functions in our component for using that function to make the HTTP request and to be able to use them from our react components.
To consume the Rest API, I have created a component that will have all the requests, you can idea from this component depending on how your app works.

Crudtourists.js

import React, { useState, useEffect } from "react"
import Form from "./Addtourist"
import Tablelist from "./Touristtable"
import 'bootstrap/dist/css/bootstrap.min.css';

import { restHelper } from "../httphelpers/restHelper"

const Crudtourists = () => {
    const [tourists, settourists] = useState(null)

    const url = "http://restapi.adequateshop.com/api/Tourist"
    const api = restHelper()

    useEffect(() => {
        gettourists()
    }, [])

    const postTourist = tourist => {
        api
            .postCreate(`${url}`, { body: tourist })
            .then(res => gettourists())
            .catch(err => console.log(err))
    }

    const updateTourist = (id, tourist) => {
        api
            .putUpdate(`${url}/${id}`, { body: tourist })
            .then(res => gettourists())
            .catch(err => console.log(err))
    }

    const deleteTourist = id => {
        api
            .deletedata(`${url}/${id}`, {})
            .then(res => gettourists())
            .catch(err => console.log(err))
    }

    const gettourists = () => {
        api
            .get(`${url}`)
            .then(res => {
                if(res && res.data)
                {
                    settourists(res.data)
                }
            })
            .catch(err => console.log(err))
    }
    if (!tourists) return null

    return (
        <>
            <h3>New user</h3>
            <Form postUser={postTourist} />
            <div className='container-fluid'>
                <h3>All users</h3>
                <Tablelist
                    tourists={tourists}
                    settourists={settourists}
                    postTourist={postTourist}
                    updateTourist={updateTourist}
                    deleteTourist={deleteTourist}
                />
            </div>
        </>
    )
}

export default Crudtourists

 

Ashok Patel

I'm a software engineer, having good experience in software programming web designing with great command on ASP.NET, React JS, Angular JS,.NET Core HTML5, JavaScript, T-SQL, JQuery.
Also have great experience in Electronics and electrical engineers design.
I like to do RND and Research.

Your Header Sidebar area is currently empty. Hurry up and add some widgets.