|
1 | 1 | import { useAppDispatch, useAppSelector } from 'app/store/storeHooks';
|
2 | 2 | import { selectListImagesQueryArgs } from 'features/gallery/store/gallerySelectors';
|
3 | 3 | import { offsetChanged } from 'features/gallery/store/gallerySlice';
|
| 4 | +import { throttle } from 'lodash-es'; |
4 | 5 | import { useCallback, useEffect, useMemo } from 'react';
|
5 | 6 | import { useListImagesQuery } from 'services/api/endpoints/images';
|
6 | 7 |
|
@@ -80,32 +81,41 @@ export const useGalleryPagination = () => {
|
80 | 81 | return offset > 0;
|
81 | 82 | }, [count, offset]);
|
82 | 83 |
|
| 84 | + const onOffsetChanged = useCallback( |
| 85 | + (arg: Parameters<typeof offsetChanged>[0]) => { |
| 86 | + dispatch(offsetChanged(arg)); |
| 87 | + }, |
| 88 | + [dispatch] |
| 89 | + ); |
| 90 | + |
| 91 | + const throttledOnOffsetChanged = useMemo(() => throttle(onOffsetChanged, 500), [onOffsetChanged]); |
| 92 | + |
83 | 93 | const goNext = useCallback(
|
84 | 94 | (withHotkey?: 'arrow' | 'alt+arrow') => {
|
85 |
| - dispatch(offsetChanged({ offset: offset + (limit || 0), withHotkey })); |
| 95 | + throttledOnOffsetChanged({ offset: offset + (limit || 0), withHotkey }); |
86 | 96 | },
|
87 |
| - [dispatch, offset, limit] |
| 97 | + [throttledOnOffsetChanged, offset, limit] |
88 | 98 | );
|
89 | 99 |
|
90 | 100 | const goPrev = useCallback(
|
91 | 101 | (withHotkey?: 'arrow' | 'alt+arrow') => {
|
92 |
| - dispatch(offsetChanged({ offset: Math.max(offset - (limit || 0), 0), withHotkey })); |
| 102 | + throttledOnOffsetChanged({ offset: Math.max(offset - (limit || 0), 0), withHotkey }); |
93 | 103 | },
|
94 |
| - [dispatch, offset, limit] |
| 104 | + [throttledOnOffsetChanged, offset, limit] |
95 | 105 | );
|
96 | 106 |
|
97 | 107 | const goToPage = useCallback(
|
98 | 108 | (page: number) => {
|
99 |
| - dispatch(offsetChanged({ offset: page * (limit || 0) })); |
| 109 | + throttledOnOffsetChanged({ offset: page * (limit || 0) }); |
100 | 110 | },
|
101 |
| - [dispatch, limit] |
| 111 | + [throttledOnOffsetChanged, limit] |
102 | 112 | );
|
103 | 113 | const goToFirst = useCallback(() => {
|
104 |
| - dispatch(offsetChanged({ offset: 0 })); |
105 |
| - }, [dispatch]); |
| 114 | + throttledOnOffsetChanged({ offset: 0 }); |
| 115 | + }, [throttledOnOffsetChanged]); |
106 | 116 | const goToLast = useCallback(() => {
|
107 |
| - dispatch(offsetChanged({ offset: (pages - 1) * (limit || 0) })); |
108 |
| - }, [dispatch, pages, limit]); |
| 117 | + throttledOnOffsetChanged({ offset: (pages - 1) * (limit || 0) }); |
| 118 | + }, [throttledOnOffsetChanged, pages, limit]); |
109 | 119 |
|
110 | 120 | // handle when total/pages decrease and user is on high page number (ie bulk removing or deleting)
|
111 | 121 | useEffect(() => {
|
|
0 commit comments