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:
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:
AbortController
each time button is clicked, per each request. I have no idea on how to do it though.AbortController
inside useEffect
, what usually solves the problem. However, it won't be reachable from the onButtonClick
anymore.useCallback()
?)Is there a canonical way of making API calls OUTSIDE the useEffect
"component constructor"?
One way would be to make your request from within an Effect triggered by a state change.
function YourComponent() {
const [fetching, setFetching] = useState(false);
const onSuccess = useCallback((data) => {
setFetching(false);
// ...
}, [])
const onError = useCallback((err) => {
setFetching(false);
// ignore abort errors
if (err instanceof DOMException && err.name == "AbortError") return;
// do some logging
}, [])
function onButtonClick() {
setFetching(true);
}
useEffect(() => {
if (!fetching) return;
const controller = new AbortController();
apiContext.requestSomething(controller, onSuccess, onError);
return () => {
controller.abort();
};
}, [apiContext, fetching, onSuccess, onError]);
return (
<button onClick={onButtonClick}>Click me!</button>
);
}