Recently, I've been working on a React.js project where we needed to create a helper class for our application. I noticed that there are many questions regarding creating a file with multiple functions, so I decided to write an article on this topic and share the code. This way, other developers can benefit from it.
Our goal is to create a JavaScript file with reusable functions that we can import into components and call as needed. We aim to create a class that functions as a global helper class for our application, which we can use in other classes or components.
For instance, we want to perform insert, update, and delete operations using a REST API. To achieve this, we created an `httphelper` for our application. Using this helper, we can make different HTTP requests to the REST API.
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.
You can utilize the following helper in any of your React applications, as well as in any JavaScript framework such as Angular or Vue.js.
The callAPI() function is an asynchronous function that accepts endpointurl as a parameter to perform the HTTP request, along with an options object. If the options parameter is not provided (i.e., it's an empty object), default values are assigned for the defaultHTTPMethod and defaultHTTPHeaders. Otherwise, the obtained values are replaced with the default ones.
Additionally, we have another function called AbortController, which enables us to abort the HTTP request after a certain duration if the API server fails to return a response..
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,
}
}
This module simplifies the process of making HTTP requests to RESTful APIs by providing a set of helper functions with customizable options for different HTTP methods.
import React, { useState, useEffect } from "react"
import {HttpHelper} from "./path/to/restHelper.js"
Take a look at the Crudtourists.js component below. Here, I've imported the helper and utilized its functions.
Finally, we export the functions within our component to enable the usage of these functions for making HTTP requests from our React components.
For consuming the REST API, I've created a component that encapsulates all the requests. You can gain insight from this component based on how your app operates.
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://samplerestapi.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
API Interaction: It imports the restHelper function from the ../httphelpers/restHelper file. This function is used to make HTTP requests to the REST API.
Fetching Tourist Data: Upon component mount, it calls the gettourists function using the useEffect hook. This function sends a GET request to fetch tourist data from the specified URL (http://samplerestapi.com/api/Tourist). Upon successful response, it updates the tourists state with the received data.
CRUD Operations: It defines functions postTourist, updateTourist, and deleteTourist to handle POST, PUT, and DELETE operations, respectively. These functions utilize the api object obtained from restHelper to make the corresponding API requests. After each operation, it fetches the updated tourist data using gettourists.
Rendering: It renders a form (Form) component for adding new tourists and a table (Tablelist) component for displaying all tourists. It passes necessary props to these components for managing data and performing CRUD operations.
This component having the logic for CRUD operations related to tourist data, providing a user interface for adding, updating, and deleting tourists.