Skip to content

Commit d251624

Browse files
committed
chore: improve some comments
1 parent 09d9266 commit d251624

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

src/use-request.ts

+8
Original file line numberDiff line numberDiff line change
@@ -17,38 +17,46 @@ export const useRequest = <T>(
1717
});
1818

1919
useEffect(() => {
20+
// Cleanup on unmount
2021
return () => {
2122
ref.current.abortController?.abort();
2223
};
2324
}, []);
2425

2526
if (isEqualWith(ref.current.deps, deps)) {
27+
// If dependencies haven't changed, return cached state
2628
return {
2729
data: ref.current.data,
2830
loading: ref.current.state === 'loading',
2931
error: ref.current.error,
3032
};
3133
}
3234

35+
// Cancel previous request
3336
ref.current.abortController?.abort();
3437

38+
// Update the dependencies and state
3539
ref.current.deps = deps;
3640
ref.current.state = 'loading';
3741
const abortController = new AbortController();
3842
ref.current.abortController = abortController;
3943

44+
// Make the request
4045
request(abortController.signal)
4146
.then((data: T) => {
47+
// Only update if the request hasn't been aborted
4248
if (abortController.signal.aborted) return;
4349
ref.current.data = data;
4450
ref.current.state = 'done';
4551
})
4652
.catch((err: unknown) => {
53+
// Only update if the request hasn't been aborted
4754
if (abortController.signal.aborted) return;
4855
ref.current.error = err;
4956
ref.current.state = 'error';
5057
})
5158
.finally(() => {
59+
// Trigger a re-render to reflect the state changes
5260
setVersion((v) => v + 1);
5361
});
5462

0 commit comments

Comments
 (0)