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
The post React Js- Fetch data from API using hooks appeared first on Software Development | Programming Tutorials.
Read More Articles
- how to create common helper class in React JS using ES6 which is used by another component?
- How to create helper file full of functions in react native?
- how to create a class and another classes extends that class in react js
- How do I create a class decorator for mixing new methods into a React component when using Typescript?
- How to use common component between Create React APP(CRA) and Gatsby where component consists of <Link> tag?
- how to import Helper class in react
- how to create dynamic css class in react
- How to create Chai/Mocha unit tests for a ES6 class React component?
- How to create a local react library project with common components, and import that project locally
- How to create algolia autocomplete custom renderer using react class component
- How do I create a javascript helper function / class that can perform an async task before each exposed method
- How do I create an array of objects in a React class component through a for loop to be mapped in a functional component?
- How to create a React app directly in the current folder
- How to create unique keys for React elements?
- How to create dynamic href in react render function?
- How is ESLint integrated into Create React App?
- How to create multiple page app using react
- How to create a React Modal (which is appended to <body>) with transitions?
- How to create text border in React Native?
- How to create forms with React and Rails?
- Create an instance of a React class from a string
- How to declare defaultProps on a React component class using TypeScript?
- How to generate sourcemaps in create react app?
- How do I export more than one class component with React JS?
- How do I create a TypeScript type definition for a stateless React component?
- How to create two columns with space beetwen in react native - flatList
- How to not show warnings in Create React App
- How to implement skipWaiting with Create React App?
- How can I repeat a pattern image to create a background in React Native?
- how to create React search filter for search multiple object key values
- Pass Parameter To Algolia React Instant SearchBox
- React Google Maps doesn't import
- Accessing value through material ui ListItemText component
- How to cleanup async tasks created outside useEffect
- Is it possible to change default fallback message i18n-js?
- Not able to style three element inside a flex box for small devices
- How to Fix: Cannot read property 'total' of undefined
- React Hook useEffect has a missing dependency array
- React Admin The dataProvider returned an empty response for 'update'
- What is the difference between Nav.Link vs Link vs NavLink in react router DOM and react bootstrap?
- React Semantic-UI: Dropdown.Menu / Problem
- AceEditor setValue() not triggering my React App's onChange function
- Material-UI get all rows from DataGrid
- How to replace a string in parameters from query with variables in ReactJS
- Grunt, Jasmine, Phantom, React Unit Testing: React throws on ReactElementValidator
- Adding a Component to an other from a third one
- styled-components makes input range not work
- React Router master-detail: children component don't render new view until page refresh
- Sass flex order does nothing on generated elements
- ReactJS Call a function in render after an action
- React + Bootstrap : cannot map Tabs content
- State is not updating immediately in React.js
- 401: unauthorized issue in Web API .net core C#
- React: How to call a function from another file?
- Docker + Flask + React + Axios + http-proxy-middleware failing with "Error occured while trying to proxy to..."
- How to disable typechecking when using a logical operator or when the final result is allowed to be undefined
- ANT Design Push Pull Confusion
- Change outline for OutlinedInput with React material-ui
- Comment reply system with React Quill and Firebase Firestore
- Transforming React State Object into correct JSON schema
- Going back to home page on refreshing/reloading or manually entering the URL in react
- target array by passing argument in function in js/react
- How do you test a redux connected react component by exporting it as a PureComponent?
- How to keep previous states when adding new ones
- Show overlay only once on page entrance (not route change). HowTo?
- Error: ./src/App.js Attempted import error: 'Switch' is not exported from 'react-router-dom'
- Call child component method from parent in react
- Reuse mutations without duplicating code in Apollo + React?
- React.js Route - previous page stays after redirection
- Abort previous running async componentDidMount
- Update initial useState of object - TypeScript , ReactJS
- React - layouting components
- React cloneElement and component instance
- Implement Read More feature for multiple textual children in React
- How to make my reducer reusable using Redux toolkit?
- Dynamic Header Titles with React
- How to get Reacjs input text value without any form
- React MUI components (Slider/Select) "onChange" doesn't change value immediately (provide result of previous click)
- Module Build Error: pngquant ENOENT - webpack build succeeds on local OS X, fails on AWS Ubuntu 16.04 server
- New line '\n' not recognized inside TextField in React
- Redux Not Updating in Component Synchonously
- How to use react router (createBrowserHistory) on Microsoft IIS to make routing working?
- How to hold for 5 sec after api response and then go next in react native
- How to set a timeout using axios without cancelling API call?
- Font awesome icons are not displaying react
- Passing vars from -> to functional components in React using react-router-dom (<Route>)
- Function onChangeAnswers in the checkbox what he does
- Removing the last item of an array with filter won't re-render react component
- setState works every second call
- React.js with Node.js Rest API
- React effect infinite re-renders when fetching data
- Can I extract my import statements to different files?
- React - pixel ratio - set 2x 3x images for retina devices
- FCC Pomodoro Clock failing in-built tests
- Why is React Bootstrap Card not showing in the browser? The page is empty despite the component being used
- Displaying time data on horizontal calendar
- Cannot assign to read only property 'exports' of object '#<Object>' react and socket
- How to use a react component for showing Google Maps InfoWindow
- Unhandled Promise Rejection: Syntax Error
- 'string' is declared but its value is never read
- How do I dynamically adjust the size of the React chart 2 pie chart
- How to use useSwiper outside a Swiper instance?
- How to change React component tag to jsx tag name with condition properly?
- Local Storage - React Native
- How to write unit test for Material UI slider? "Error: Cannot read property 'addEventListener' of null" thrown when attempting to render component
- Unable to limit the data and disable the button using reactjs?
- How to upload a photo with React and Next?
- How to implement login authentication using react-redux?
- I want to get attachments as well that comes with the message Gmail API
- Insert tab character into SlateJS text editor
- How to add RTL support for Material UI React
- How can i split a column of list in different rows in bootstrap
- Jest React Example
- React - TypeError: Cannot read property of undefined
- Loading font icons with React
- why my React setstate is not updating immediately?
- Unhandled Rejection (Error): Could not load settings for 'WebPortal' - ASP.NET Core React
- Applying ID to canvas with react-three-renderer
- Objects are not valid as a React child (object with keys {id, value, name}). If you meant to render a collection of children, use an array instead
- Receive unexpected token ), on webpack config
- Changes do not affevt on the map function and do not show :)
- How to declare a type in typescript based on the keys mentioned in the same type?
- Using class instances in react state
- React datepicker short month how to display three letters only
- Is there a way to dynamically set Object in ReactJS?
- Close Popover on click in child component
- How to dispatch actions from Navigation bar in React
- Material UI React - Autocomplete - How to reset the internal state
- React - Context issue - raphael-react
- Issues in making Routes in Reactjs
- Search in the multiply tree view doesn't work properly
- Multiple Queries using Apollo Client and React
- Web foreground push notification is not popping up integrated using Firebase in Reactjs
- Get binary data with XMLHttpRequest in a Firefox extension with AXIOS
- How to fix. TypeError: Cannot read property 'user' of null
- I am unable to create react app using npx
- how to group array of objects by value in reactjs / javascript
- Render specific react component based on the URL
- Give React Prop an interface
- I want to fetch data and display it in a react page
- How do I offset Material-UI Popper (popper.js library) position on y-axis?
- Spring-React frontend-maven-plugin not working
- React-router-dom redirect not working with withRouter HOC (react-redux)
- Custom word translator in React
- Make child of Material UI Grid item stretch to fit the remaining height of the parent container
- setState in useEffect not update
- React checkbox. DRY out onChange function to handle all checkboxes
- Material UI Button - How can I use "::first-letter" pseudo element selector with MuiButton class?
- Wait a result of a async function before render react routes
- Is it possible to use material-ui button navigation with react-router?
- Best practice: prepare props only once for rendering
- How to add a link in Leaflet popup?
- Upload file (image) by .put() method to firebase-storage get unexpected result
- React passing img src from Data.js to index.js but is showing as [object model] in page source
- how to send key[op]:value using axios params in js
- Meteor react render subscribe
- Getting blank page on using Route | React
- React custom hook for MouseEventHandler with Typescript
- refetch different query from retry of another query in React Query
- TypeScript | Can't loop over a custom type Object
- React JS/Typescript Axios Variable Assignment
- How to mutate CSS custom property color with CSS-in-JS?
- How to delete The array item in react js?
- React JS: How to make this delete button work
- How to make an API request using axios?
- React Unhandled Rejection (Invariant Violation)
- React Material UI DropDown Menu Doesn't Work
- semantic ui make content div scrollable but not the whole page scrollable? (meteor + react)
- componentDidUpdate() does not update items on the go
- React does not recognize the prop passed to a styled-component within Material UI
- Testing subsequent function call on an Async function from React function component
- How to disable AMD on 4 files and load them in order with webpack
- How to override MUI button, so that the color prop still works
- Parse can't find localStorage variable in React Native
- How do I remember a React-Router URL parameter when navigating away and then back to a page?
- React Firestore data retrieval into array not working
- Component re-render when state is an object of objects
- Can you tell me why the second in incrementing in even numbers in the stopwatch?
- How to import "useAccordionButton"?
- Material UI Autocomplete Styles
- RTK Query query not refetching after mutation
- Refs are always null inside modal component
- TypeScript Removing Repetitive Property Assignment with React-Redux
- How to update specific object in array NodeJS, MongoDB
- Posting data using node-fetch in a react component malfunction
- How to get the last children in a deeply nested array with objects
- Dynamically Cover Image with Rectangle in HTML/CSS
- How to update react hook from another file?
- How to use async await in React using the axios in the API call
- Ho can i return a Custom HTML div in React JS?
- How to only use one loop per multiple function executions in a redux action
- Return highest number and associated name from object in Javascript
- Prevent Component Rendering when i use navigate in react router dom v6
- Node js - ejs: How to run password check on login/register form
- Passing props from one class component to other in react js
- Best way to change image and description onClick with react hooks
- Jest - Unit test failing for asynchronous operation
- Checking if http is success or fail Reactjs
- Function passed and invoked in child component doesn't have access to parent state value
- I need to have some fields in ui-schema which do not exist in schema section