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
- React class component renders twice on Chrome only
- 'Access-Control-Allow-Credentials' header in the response is ' ' when trying to send a POST request to an API using Axios
- How to render component by referring its string type of name?
- React component not re-rendering with state update
- React hooks, reducer, context & initial state object. How do I make my API-call?
- Can you run a function in an input value in React?
- Fetching data using props - Cannot read properties of undefined (reading 'map')
- Spread operator with React useState // Populating state from Firebase
- React list isn't re-rendering table after sorting elements in state
- How to loop over Typescript Array in ReactJS?
- How to add onChange to react-datetime when using formik?
- Component re-renders wierdly on state change
- React Native multi line TextInput, text is centered
- I just want to connect react and socket io in a simple way, but the connection cannot be made
- redux call reducer with action
- How do I call an actioncreator with details of the rendered DOM element in Flux?
- Selecting something that isn't a div or other standard selector?
- Want dynamically add table row in react js
- What do these JSX elements with no names mean?
- how to change initialState in react-redux
- Passing Props (img url ) using React-Modal
- how to resolve "Prop `id` did not match. Server: "react-tabs-30" Client: "react-tabs-0" console issue?
- Unable to host my react app on github. Unable to deploy
- React draft-js color picker lost inline style
- How to bypass policies when testing with hyperstack
- × TypeError: Cannot read property 'pathname' of undefined
- Render blocking react.js and pageSpeed / page rank
- Highcharts Gantt - Set max height and scrollbar on yAxis
- How to keep the cup always in the middle without decreasing image size even when we decrease the window size?
- How to override Material UI .MuiContainer-maxWidthLg?
- How can I prevent all of my accodion components being toggled when clicked in React?
- Communication child-parent ReactJs
- 'Too many re-renders' when checking for length of input
- Active class for button groups in ReactJs
- react-router is not filling params
- How do I set container within React Material UI's AppBar Component?
- How to prepend a list Item in react correctly
- Avoid select tag's value being reset to default when changing selected option values through React state
- i cant handle data and save using useState after use await
- How can I use regular expressions in react js so that I can you use that in firestore collection name
- how to get the values that were sent from axios.post in the backend
- i have problem with converting function in class component to functional
- setState not maintaining set value after value set with Callback
- React HMR does not render even though an update is detected
- How to debounce async formik/yup validation, that it will validate when user will stop entering data?
- making changes to svg element on the fly
- Need help on Store and retrieve data using react js, node js, MySQL and webpack
- Why is fetch PUT giving argument error (0 for 1) in React when talking to Rails?
- Where to put useDispatch and bindActionCreators in a project?
- I can't get a value out of Redux store in App component
- getting undefined value of imported function in react
- How to get the index of the table into columns array in antd table
- Not able to pass Data From Nested File Upload React Component to Parent Component
- React - change state right after previous state change was rendered
- Trouble getting an Authentication Token using Axios for React
- How do I get data from Express endpoint in a React component?
- React Facebook Login with Enzyme mount - TypeError cannot read property 'parentNode' of undefined
- Possible to self refence element inside style={}? - ReactJS
- Push destructured values from one array to another
- React: clicked link versus direct link
- How do I trace React Emotion Styled Components back to their location in the source code
- Limitation for Charachters to show in div's
- State is not getting initialized to the initial state
- How to trigger a child component validation from parent onSubmit - react
- next JS apollo Link change clears query, have to refresh page for query to run
- Using Typescript in Reactjs
- Converting to same date format using format of Moment JS gives invalid date
- Cannot read property name of null reactjs
- Need help implementing react-hook-form with Gatsby.js: form won't even post values to console
- React-intl, Redux-Form combine and raise warnings
- React.js modal not show with Semantic Ui
- Why am I unable to access a Redux store in a child React component?
- Multi Language React DatePicker
- How can i connect redux with localStorage so that when updating the like on the page does not disappear
- Why am I getting error "No valid versions available for undefined" while installing create-react-app
- Gatsby.js: Preprocessing Relative Path Links in Markdown
- Button within a tab to switch tabs using Ant Design in React?
- webpack --watch not working properly
- How to calculate number of tuesday in the selected date range using reactjs?
- TypeError: Cannot read property 'vote' of null in render view
- Load login page without Sidebar, Navbar and Dashboard in React
- interface not matching data
- How do I extract the file names from an "upload file" component and display them in a list on the UI?
- How to conditionally render a list item based on if id matches a websocket object's id
- JEST- ReferenceError: React is not defined using jest in .NET MVC 4 app
- React cannot render font awesome icon
- styled-components local variable
- IIS rewrite condition for React MVC App
- What are differences between redux, react-redux, redux-thunk?
- sessionStorage.getItem null in react
- Patterns in React (wrapper)
- Newly added items to list do not get _id key prop added until hard refresh
- How should I pass my prop to get a valid Array[Object]
- Redux - Why normalize?
- Testing a component that uses useEffect using Enzyme shallow and not mount
- React component children detect if empty / null before render
- JavaScript - Adding a parameter to a success callback
- Sorting table in react. How it's possible when only one column works?
- How to update a store from other store function
- Dynamically updating a highcharts object after data refresh in React
- How to delete an entry from a Record in typescript,based on the Id
- What is the technical difference between .jsx and .js files
- Call method from view in reducer
- How to get js-cookies?
- Making a back button using previous state of the array index
- state value is undefine in react js
- How can I pass data from one card, in a list of cards, to a dialog?
- How to hide/show a component inside another component in ReactJS
- Is there a way to override the colors in Ant design Switch Component
- React Redux - Mapping over array while rerendering only components holding changed object (in array)
- div alignment is not coming properly
- Connect returns an object, but how do I get it to return a function?
- AXIOS Get API Response in new window
- How do I fix TypeError: books.map is not a function that my code generates?
- ReactJS Spread Operator
- Get list of optional props of a component in reactjs
- How to filter and sort nested objects? ReactJS
- TypeError: event.preventDefault is not a function
- Hetting error in react build with webpack
- Global React does not play nice with AMD React
- Linking to a component from the same component doesn't work
- Triggering event with react-ga returns "Command ignored. Unknown target: undefined"
- React 15 - Finding offsetTop property of an element
- (Reactjs) How to submit the file immediately after selected the file
- If i`m isLogged abd refresh page, i will redirect on main page
- React: Keypress listener on div
- post request not working in react-native redux
- ReactJS map through an array with objects
- Axios returning undefined in React component
- Failed prop type error but items are loaded
- Implementing javascript / json objects in ReactJS
- How to add material-ui component by innerHTML?
- React: accessing the component that triggered a synthetic event
- How to get out of a forEach loop once a value is true using firebase and react
- Using useRef hook, modify CSS style for a react component
- Convert array to object without sorting keys in javascript
- How to implement validation/restriction in react-datepicker
- Gradient font awesome IN REACT
- React js convert css to css for react
- How to display a div based on loggedin or not in react?
- How to test asnyc code with Jest ( or test "image.onload" with jsdom )
- @typescript-eslint/no-unused-vars false positive in type declarations
- How to get rid of duplicates in javascript?
- Getting a Typescript error saying, some type is not assignable to parameter of type 'ReducerWithoutAction<any>'?
- React useState in functional components not updating the property values immediately
- Align Image and Text in Horizontal Direction in React
- I think render works twice
- How to call useEffect when browser is resized
- Redux: Cannot read property 'getState' of undefined
- Create nested object in javascript
- How to implement login authentication using react-redux?
- React useEffect fetch hook makes endless calls despite array parameter
- Issue with "M" in BEM with React CSS Module
- Summatory React
- How do I call a Prismic API inside next.js getInitialProps?
- React form using Express API returns Cannot POST /
- React responsive UI is not rendered with tiny text on mobile devices
- How do i set Uploadcare's multiple upload field to give a array of URLs instead of a URL that references a group of images?
- How to fix the error argument of type boolean or undefined using react and typescript?
- Reactjs: how to put the html template in a separate file?
- AmplifyAuthenticator with react-router-dom
- React native: Component not defined? Can't import?
- Check if shortcut is present on homescreen as in normal mobile apps
- Going to the router URL directly is not working
- Why react-testing-library is showing reference error
- Avoid rendrawing chart, D3
- Chakra UI - Checkbox Group
- What is the equal code for OnChange on React Class Component , on React Function Component
- Applying Filter after Fetching data from api in React
- How to send React hook's setter to another component