I’m hopelessly trying to find a way to send, receive and process an API request in React component, but executed from within an event handler, not directly in useEffect
. The requirements are:
- Using Axios to easily send async requests
- The request needs to be cancelled when React component unmounts
- I want this solution to work in strict mode (sending two requests will be fine, but it would be cool if someone shown solution for a single request only)
My current approach suffers from the dreaded auto-cancelling of the request, because the AbortController
needs to be instantiated in the root scope of the component (otherwise it will not be reachable both from useEffect
cleanup function and from the event handler.
The sekeleton component looks like following:
import { useState, useEffect } from 'react'
import { Button } from 'react-bootstrap'
import { ServiceContainer } from '../../../services/ServiceContainer.ts'
function Login(props: { serviceContainer: ServiceContainer }) {
const [ email, setEmail ] = useState("");
const abortController: AbortController = new AbortController();
function onSuccess() {
// Do sth
}
function onFailure() {
// Do sth else
}
function onButtonClick() {
// This calls Axios internally
props.serviceContainer.ApiClient.SomeAction(email, abortController, onSuccess, onFailure);
}
useEffect(() => {
return (() => {
abortController.abort();
});
});
return(
<Button onClick={onButtonClick}>Click me!</Button>
);
}
export { Login }
The code above is doomed to fail in Strict Mode, because the abortController.abort()
will get called immediately and prevent request from being sent in the first place.
These are potential solutions and workarounds I thought of:
- Constructing new
AbortController
each time button is clicked, per each request. I have no idea on how to do it though. - Moving
AbortController
insideuseEffect
, what usually solves the problem. However, it won’t be reachable from theonButtonClick
anymore. - Extracting the whole request part into separate component. I’d need to pass through props all required parameters (email in the above example) and a way to send back a callback about the result (possibly a set* function? Or an actual callback method created via
useCallback()
?) - Replacing changing state of the component (Enter-Request-Success/Failure) into routing and switching between components (but then passing data will be tricky).
Is there a canonical way of making API calls OUTSIDE the useEffect
“component constructor”?