UNPKG

@excentone/spfx-react

Version:

Contains custom ReactJs components and hooks intended to use when developing SharePoint Framework (SPFx) Web components.

48 lines (46 loc) 1.74 kB
import { assertNever } from "@fluentui/react"; import { useMemo, useReducer, useState } from "react"; import { isFunction } from "@excentone/spfx-utilities"; const reducer = (prev, command) => { if (!command) throw new ReferenceError('command is empty.'); switch (command.type) { case 'set': return command.params; case 'increment': return prev + 1; case 'decrement': return prev - 1; default: assertNever(command.type); } }; export const useCounter = (optionsOrInitialValue) => { const [options, setOptions] = useState(() => { if (typeof optionsOrInitialValue === 'number') return { initialValue: optionsOrInitialValue, defaultValue: optionsOrInitialValue }; return { initialValue: 0, defaultValue: 0, ...optionsOrInitialValue }; }); const [count, dispatch] = useReducer(reducer, options.initialValue); const operations = useMemo(() => ({ set: value => dispatch({ type: 'set', params: value }), setMax: setValue => setOptions(prev => ({ ...prev, maxValue: isFunction(setValue) ? setValue(prev.maxValue) : setValue })), reset: () => dispatch({ type: 'set', params: options.defaultValue }), increment: () => !options.maxValue || count <= options.maxValue ? dispatch({ type: 'increment' }) : void 0, decrement: () => !options.maxValue || count <= options.maxValue ? dispatch({ type: 'decrement' }) : void 0, }), [options]); return [count, operations]; }; //# sourceMappingURL=useCounter.js.map