score:3
Accepted answer
const usehttpreqhandler = () => {
const [result, setresult] = usestate();
const [loading, setloading] = usestate(false);
const apimethod = usecallback(async ({url , data , method}) => {
let options = {
method,
url,
headers: {
'accept': 'application/json',
'content-type': 'application/json;charset=utf-8'
},
data
};
setloading(true);
try {
let response = await axios(options);
const updateddata = await response.data;
setresult(updateddata);
setloading(false);
} catch (e) {
console.error(e)
setloading(false);
}
}, [setloading, setresult])
return [loading, result , apimethod];
};
and then show a spinner in your component while loading
is true
.
untested and probably not working, but you might get the idea:
const mycomponent = () => {
const [loading, apiresult, apimethod] = usehttpreqhandler();
const captchvalidation = usecallback(() => {
const x = result.tostring();
const y = inputvalue.tostring();
apimethod({url: 'your url', data: {"email": email}, method: 'post'})
if (x === y) {
console.log("entered here in api part")
if(apiresult){
alert("success")
}
}
else {
alert("fail")
}
}, [apimethod, apiresult])
return (
<>
{
loading ? (<spinner />) : (<button onclick={captchvalidation}></button>)
}
</>
)
}
Source: stackoverflow.com
Related Query
- Axios request in react for handling http request
- How do I create configuration for axios for default request headers in every http call?
- React axios Error: Request aborted for delete request in Firefox but not in Chrome
- Axios get request returns undefined for the first time in React
- Getting Bad request for POST request using Axios and CORS in Django and react app
- ReactJS- Pass the JWT token as Authorization in axios method for http request
- React axios request asks for UseEffect cleanup function to cancel all subscriptions and asynchronous tasks
- Handling http error in react for path not found
- React fullstack exercise part5 async/await syntax and promises for the HTTP request
- Error handling for an api request in React
- React and TypeScript—which types for an Axios response?
- Handling Axios error in React
- How to implement long polling for React + axios
- is there any good Http library for React flux architecture
- How to add global loading/spin effect in axios interceptor for a React project
- React Axios - C# WebAPI request token fails without a server error
- Error: Request failed with status code 401 axios in React JS
- Axios is caching somehow my get user request react native
- How can I create a progress bar for an API request in React Native?
- Express Session Cookie Not Being Set when using React Axios POST Request
- Axios 400 Bad request in React
- react with Rails 5, getting CSRF error for post with axios
- Use componentWillMount or componentDidMount lifecycle functions for async request in React
- Using different API url for development and production with React and axios
- react formik - fill form inputs with data after http request
- React and Axios GET request issue with Safari on MacOs and iOs
- how to show error message in react js when http request send?
- Using React and axios for curl
- axios get request for real-time data
- Delete request with axios - React
More Query from same tag
- Is it possible for button onClick to fire twice before being disabled since setState is asynchronous?
- useLocation() is not working even inside the Router context
- How can I prevent React from unmounting/remounting a component?
- `react-hook-form` display error message on empty input
- Webpack chunking. No content appearing - chunks not loaded
- Render a component with different states with a click
- How to fix breakpoints only updating on reload?
- React Tabulator - header filter for specific select column - remove 'X'
- Cannot upload id by using uuid on firebase with React.js
- React bootstrap table not changing sizePerPageList
- Open links with React.createRef()
- Cross-Domain Session Cookie (Express API on Heroku + React App on Netlify)
- Jest finds tests but doesn't collect coverage
- Importing SVG files dynamically in NextJS
- Passed parameter is undefined in a function, and in the callback. Defined elsewhere
- Redux state change does not rerenders datatable
- React.JS - ComponentDidUpdate Method Does Gives Infinite Loop for Axios Calls
- onClick on <li> does't trigger
- Node js allow Access-Control-Allow-Origin for all domain
- React: Dispatch not firing on route change
- CSS arrange SVGs into offset grid
- How to test for a `click` event on the icon button of the `material-ui` AppBar?
- Sliding animation in ReactJS
- request body is empty in django
- set state of variable inside an inner component
- Why is my state variable not getting passed as prop to a child element?
- How to trigger animation on state change with styled-components in ReactJs
- How to get the current row of list of strings with map()
- How to use Graphql typescript types in react
- Components not re render on state change