Cancelling a Redux Thunk 3.0 Async Action
Provide an example of how to cancel an asynchronous action created by Redux Thunk 3.0 using AbortController to prevent setting state on an unmounted component.
// Action for fetching some data
const fetchData = () => {
// This will hold the AbortController instance
let abortController = new AbortController();
return async (dispatch) => {
try {
// Signal to the fetch API that it supports aborting
const response = await fetch('https://api.example.com/data', {
signal: abortController.signal
});
// Only proceed if response is successful
if (response.ok) {
const data = await response.json();
dispatch({ type: 'FETCH_SUCCESS', payload: data });
} else {
dispatch({ type: 'FETCH_FAILURE' });
}
} catch (error) {
if (error.name === 'AbortError') {
// Ignore because the fetch was cancelled
console.log('Fetch aborted');
} else {
// Handle other errors
dispatch({ type: 'FETCH_ERROR', error });
}
}
};
};
This snippet creates an asynchronous Redux action using Thunk middleware. It uses AbortController to cancel the fetch request when needed.
// Usage in a React component
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { fetchData } from './pathToYourActions';
const MyComponent = () => {
const dispatch = useDispatch();
let abortController = new AbortController();
useEffect(() => {
dispatch(fetchData(abortController));
// Clean up function that aborts the fetch when the component unmounts
return () => abortController.abort();
}, [dispatch]);
// ... component logic
};
This snippet shows how to use the fetchData action within a React component. It handles the component's lifecycle with useEffect to ensure the fetch operation is aborted when the component unmounts.