source: imaps-frontend/node_modules/react-use/esm/useStateList.js@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 2.4 KB
Line 
1import { __assign } from "tslib";
2import { useMemo, useRef } from 'react';
3import useMountedState from './useMountedState';
4import useUpdate from './useUpdate';
5import useUpdateEffect from './useUpdateEffect';
6export default function useStateList(stateSet) {
7 if (stateSet === void 0) { stateSet = []; }
8 var isMounted = useMountedState();
9 var update = useUpdate();
10 var index = useRef(0);
11 // If new state list is shorter that before - switch to the last element
12 useUpdateEffect(function () {
13 if (stateSet.length <= index.current) {
14 index.current = stateSet.length - 1;
15 update();
16 }
17 }, [stateSet.length]);
18 var actions = useMemo(function () { return ({
19 next: function () { return actions.setStateAt(index.current + 1); },
20 prev: function () { return actions.setStateAt(index.current - 1); },
21 setStateAt: function (newIndex) {
22 // do nothing on unmounted component
23 if (!isMounted())
24 return;
25 // do nothing on empty states list
26 if (!stateSet.length)
27 return;
28 // in case new index is equal current - do nothing
29 if (newIndex === index.current)
30 return;
31 // it gives the ability to travel through the left and right borders.
32 // 4ex: if list contains 5 elements, attempt to set index 9 will bring use to 5th element
33 // in case of negative index it will start counting from the right, so -17 will bring us to 4th element
34 index.current =
35 newIndex >= 0
36 ? newIndex % stateSet.length
37 : stateSet.length + (newIndex % stateSet.length);
38 update();
39 },
40 setState: function (state) {
41 // do nothing on unmounted component
42 if (!isMounted())
43 return;
44 var newIndex = stateSet.length ? stateSet.indexOf(state) : -1;
45 if (newIndex === -1) {
46 throw new Error("State '" + state + "' is not a valid state (does not exist in state list)");
47 }
48 index.current = newIndex;
49 update();
50 },
51 }); }, [stateSet]);
52 return __assign({ state: stateSet[index.current], currentIndex: index.current, isFirst: index.current === 0, isLast: index.current === stateSet.length - 1 }, actions);
53}
Note: See TracBrowser for help on using the repository browser.