Skip to content

Commit f335dda

Browse files
authored
fix: useAbortSignal to work with React 18 (#35)
* useAbortSignal that works in react 18 * update changelog
1 parent a1daf96 commit f335dda

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## [Unreleased]
44
### Changed
55
- fix build for UMD
6+
- fix: useAbortSignal to work with React 18 #35
67

78
## [2.1.0] - 2021-12-23
89
### Changed

src/index.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
useLayoutEffect,
55
useReducer,
66
useRef,
7+
useState,
78
Dispatch,
89
Reducer,
910
ReducerState,
@@ -18,17 +19,17 @@ const isClient = (
1819
const useIsomorphicLayoutEffect = isClient ? useLayoutEffect : useEffect;
1920

2021
const useAbortSignal = () => {
21-
const abortController = useRef<AbortController>();
22-
if (!abortController.current) {
23-
abortController.current = new AbortController();
24-
}
22+
const [controller, setController] = useState(() => new AbortController());
23+
const lastController = useRef(controller);
2524
useEffect(() => {
2625
const abort = () => {
27-
(abortController.current as AbortController).abort();
26+
lastController.current.abort();
27+
lastController.current = new AbortController();
28+
setController(lastController.current);
2829
};
2930
return abort;
3031
}, []);
31-
return abortController.current.signal;
32+
return controller.signal;
3233
};
3334

3435
export type AsyncActionHandlers<

0 commit comments

Comments
 (0)