@react-hookful/core
Advanced tools
+18
-0
@@ -6,2 +6,20 @@ # Change Log | ||
| # [0.2.0](https://github.com/Frantss/react-hookful/tree/master/packages/core/compare/@react-hookful/core@0.1.0-alpha.9...@react-hookful/core@0.2.0) (2020-11-01) | ||
| ### Bug Fixes | ||
| * **core:** renamed useStateObject to useObject ([7ba7ae0](https://github.com/Frantss/react-hookful/tree/master/packages/core/commit/7ba7ae09ba8cedac00f83924ba8813cb2277d798)) | ||
| ### Features | ||
| * **core:** added useArray ([79861c1](https://github.com/Frantss/react-hookful/tree/master/packages/core/commit/79861c10bf1ce3a6dc9693e116fc3e3c2754769b)) | ||
| * **core:** improved typings ([ba1edc1](https://github.com/Frantss/react-hookful/tree/master/packages/core/commit/ba1edc17dd8740783daa507a05be815176f84675)) | ||
| * **core:** removed useAsyncFunction ([991990e](https://github.com/Frantss/react-hookful/tree/master/packages/core/commit/991990e19e7a22a460a997c4558dbf09979e2aa2)) | ||
| # [0.1.0-alpha.9](https://github.com/Frantss/react-hookful/tree/master/packages/core/compare/@react-hookful/core@0.1.0-alpha.7...@react-hookful/core@0.1.0-alpha.9) (2020-10-29) | ||
@@ -8,0 +26,0 @@ |
@@ -1,2 +0,2 @@ | ||
| "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react");const t=t=>{const r=e.useRef();return r.current||(r.current=t),r.current},r=t=>{const[r,s]=e.useState(t),u=e.useCallback((e=>s((t=>({...t,...e})))),[s]),a=e.useCallback((()=>s(t)),[s,t]),c=e.useCallback((()=>s({})),[s]);return[r,{set:s,merge:u,reset:a,clear:c}]},s=e=>(e=>"function"==typeof e)(e)?e():e;exports.useAsyncFunction=(t,s=[],u=[])=>{const[a,c]=r({data:null,loading:!0,error:null}),n=e.useCallback((async()=>{try{const e=await t(...s);c.merge({data:e,loading:!1})}catch(e){c.merge({error:e,loading:!1})}}),u);return e.useEffect((()=>{n()}),u),a},exports.useConstant=r=>{const u=e.useRef();return t((()=>(u.current||(u.current={state:s(r)}),u.current.state)))},exports.useCounter=t=>{const[r,u]=e.useState(t),a=e.useCallback(((e=1)=>u((t=>t+e))),[u]),c=e.useCallback(((e=1)=>u((t=>t-e))),[u]),n=e.useCallback((()=>u(s(t))),[u,t]);return[r,{set:u,inc:a,dec:c,reset:n}]},exports.useEffectOnce=t=>{e.useEffect(t,[])},exports.useFreezedCallback=t,exports.useStateObject=r,exports.useToggle=t=>{const[r,s]=e.useState(t),u=e.useCallback((()=>s(!0)),[s]),a=e.useCallback((()=>s(!1)),[s]);return[r,{toggle:r?a:u,setTrue:u,setFalse:a,set:s}]}; | ||
| "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react");const t=t=>{const s=e.useRef();return s.current||(s.current=t),s.current},s=e=>(e=>"function"==typeof e)(e)?e():e;exports.useArray=t=>{const[r,a]=e.useState(t),u=e.useCallback((e=>a((t=>[...t,e]))),[a]),l=e.useCallback((e=>a((t=>[e,...t]))),[a]),c=e.useCallback((e=>a((t=>[...t,...e]))),[a]),n=e.useCallback((()=>{let e=r[0];return a((([t,...s])=>(e=t,s))),e}),[a,r]),o=e.useCallback((()=>{let e=r.slice(-1)[0];return a((t=>(e=t.slice(-1)[0],t.slice(0,-1)))),e}),[a,r]),b=e.useCallback(((e,t)=>{a((s=>s.map(e,t)))}),[a]),C=e.useCallback(((e,t)=>{a((s=>s.filter(e,t)))}),[a]),k=e.useCallback((()=>a([])),[a]),p=e.useCallback((()=>a(s(t))),[a,t]);return[r,{set:a,append:u,prepend:l,pop:o,transform:b,filter:C,shift:n,concat:c,reset:p,clear:k}]},exports.useConstant=r=>{const a=e.useRef();return t((()=>(a.current||(a.current={state:s(r)}),a.current.state)))},exports.useCounter=t=>{const[r,a]=e.useState(t),u=e.useCallback(((e=1)=>a((t=>t+e))),[a]),l=e.useCallback(((e=1)=>a((t=>t-e))),[a]),c=e.useCallback((()=>a(s(t))),[a,t]);return[r,{set:a,inc:u,dec:l,reset:c}]},exports.useEffectOnce=t=>{e.useEffect(t,[])},exports.useFreezedCallback=t,exports.useObject=t=>{const[r,a]=e.useState(t),u=e.useCallback((e=>a((t=>({...t,...s(e)})))),[a]),l=e.useCallback((()=>a(t)),[a,t]);return[r,{set:a,merge:u,reset:l}]},exports.useToggle=t=>{const[s,r]=e.useState(t),a=e.useCallback((()=>r(!0)),[r]),u=e.useCallback((()=>r(!1)),[r]);return[s,{toggle:s?u:a,setTrue:a,setFalse:u,set:r}]}; | ||
| //# sourceMappingURL=index.cjs.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.cjs.js","sources":["../src/useFreezedCallback/useFreezedCallback.ts","../src/useStateObject/useStateObject.ts","../src/utils.ts","../src/useAsyncFunction/useAsyncFunction.ts","../src/useConstant/useConstant.ts","../src/useCounter/useCounter.ts","../src/useEffectOnce/useEffectOnce.ts","../src/useToggle/useToggle.ts"],"sourcesContent":["import { useRef } from 'react';\nimport { GenericFunction } from '../types';\n\n/**\n * Hook that freezed a given callback, so it is only created once in the components life.\n * It ensures the return function is always the same.\n *\n * Useful for optimizations where otherwise constant functions are recalculated every re-render\n *\n * Should the callback ever be recalculated see `React.useCallback` and `React.useMemo`.\n *\n * @param callback - The callback to freeze.\n * @returns The freezed callback.\n * @public\n */\nexport const useFreezedCallback = <T>(callback: GenericFunction<T>): GenericFunction<T> => {\n const reference = useRef<GenericFunction<T>>();\n\n if (!reference.current) {\n reference.current = callback;\n }\n\n return reference.current;\n};\n","import { useState, useCallback } from 'react';\n\n/** Setters of the state maintained by `useStateObject`\n * @public\n */\nexport interface StateObjectSetter {\n /** Merges the current state with the `arg` object. */\n merge: (arg: object) => void;\n /** State setter, the same you would get with `React.useState`. */\n set: (arg: object | ((prevState: object) => object)) => void;\n /** Resets the state back to the initial one. */\n reset: () => void;\n /** Sets the state to an empty object (`{}`). */\n clear: () => void;\n}\n\n/**\n * Hook for creating an object with several setters for ease of use. Like state merging and resetting.\n *\n * @param initialState - Initial state value.\n * @returns A tuple with the current state, and the setters.\n * @public\n */\nexport const useStateObject = (initialState: object): [object, StateObjectSetter] => {\n const [state, set] = useState(initialState);\n\n const merge = useCallback(\n (newState: object) => set(prevState => ({ ...prevState, ...newState })),\n [set],\n );\n\n const reset = useCallback(() => set(initialState), [set, initialState]);\n const clear = useCallback(() => set({}), [set]);\n\n return [state, { set, merge, reset, clear }];\n};\n","/** @internal */\nexport const isFunction = (value: unknown): value is Function => typeof value === 'function';\n\n/** @internal */\nexport const resolveValue = <T>(value: T | (() => T)): T => (isFunction(value) ? value() : value);\n","import { useEffect, useCallback } from 'react';\nimport { useStateObject } from '../useStateObject';\n\nimport { AsyncFunction } from '../types';\n\n/**\n * @public\n */\nexport interface AsyncFunctionState<T> {\n data: T;\n loading: boolean;\n error: unknown;\n}\n\n/**\n * Useful hook for running side effects and monitor their current state.\n * `loading` flag is initialized to `true` and changes to `false` once `asyncFn` has returned.\n *\n * @param asyncFn - Async function that will be run .\n * @param args - Array of arguments for that `asyncFn` takes.\n * @param dependencies - `asyncFn` will run each time the values of this array change.\n *\n *\n * @returns Object holding the current status (`loading`) and either the resulting data or an error.\n * @public\n */\nexport const useAsyncFunction = <T>(\n asyncFn: AsyncFunction<T>,\n args: unknown[] = [],\n dependencies: unknown[] = [],\n): AsyncFunctionState<T> => {\n const [state, setState] = useStateObject({\n data: null,\n loading: true,\n error: null,\n });\n\n const runAsyncFn = useCallback(async () => {\n try {\n const data = await asyncFn(...args);\n setState.merge({ data, loading: false });\n } catch (error) {\n setState.merge({ error, loading: false });\n }\n }, dependencies); // eslint-disable-line\n\n useEffect(() => {\n runAsyncFn();\n }, dependencies); // eslint-disable-line\n\n return state as AsyncFunctionState<T>;\n};\n","import { useRef } from 'react';\nimport { useFreezedCallback } from '../useFreezedCallback';\nimport { resolveValue } from '../utils';\n\n/**\n * Hook to keep a constant state value.\n * It takes an value or a resolver and maintains a reference to it though re-renders.\n *\n * Returns a getter for state value so it can be lazily set.\n *\n * `React.useState` can be used as an alternative although it should be less performing since it relies on reducers.\n *\n * Should the value change based on dependencies consider `React.useMemo`.\n * Should the value be a reference to a function consider `useFreezedCallback`.\n *\n * @param value - Either the state value or its resolver\n * @returns A getter for the state value\n * @public\n */\nexport const useConstant = <T>(value: T | (() => T)): (() => T) => {\n const reference = useRef<{ state: T }>();\n\n const get = useFreezedCallback(() => {\n if (!reference.current) {\n reference.current = {\n state: resolveValue(value),\n };\n }\n\n return reference.current.state;\n });\n\n return get;\n};\n","import { useState, useCallback } from 'react';\nimport { resolveValue } from '../utils';\n\n/**\n * Signature of the setters provided by `useCounter`\n * @public\n */\nexport interface CounterSetter {\n /** Sets the state to a given value */\n set: (value: number | ((prev: number) => number)) => void;\n /** Increments the state by a given value. Defaults to `1` */\n inc: (value?: number) => void;\n /** Decrements the state by a given value. Defaults to `1` */\n dec: (value?: number) => void;\n /** Resets the state back to its initial value */\n reset: () => void;\n}\n\n/**\n * Simple hook to keep a numeric state with some useful setters.\n *\n * @param initialValue - Either the initial value or a function that resolves to it for lazy loading.\n * @returns A tuple with the state value, and an object with its setters.\n * @public\n */\nexport const useCounter = (initialValue: number | (() => number)): [number, CounterSetter] => {\n const [value, set] = useState(initialValue);\n\n const inc = useCallback(\n (increment = 1): void => set((prevValue: number) => prevValue + increment),\n [set],\n );\n\n const dec = useCallback(\n (decrement = 1): void => set((prevValue: number) => prevValue - decrement),\n [set],\n );\n\n const reset = useCallback((): void => set(resolveValue(initialValue)), [set, initialValue]);\n\n return [value, { set, inc, dec, reset }];\n};\n","import { useEffect, EffectCallback } from 'react';\n\n/**\n * This hook its a simple wrapper of `React.useEffect` with and empty dependencies array.\n * It ensures the return function is always the same.\n *\n * @param effect - Imperative function that can return a cleanup function.\n * @public\n */\nexport const useEffectOnce = (effect: EffectCallback): void => {\n useEffect(effect, []); // eslint-disable-line\n};\n","import { useState, useCallback } from 'react';\n\n/** Setters of the state maintained by `useToggle`\n * @public\n */\nexport interface TogglerSetter {\n /** Toggles the state value between `true` and `false` */\n toggle: () => void;\n /** Sets the state value to `true` */\n setTrue: () => void;\n /** Sets the state value to `false` */\n setFalse: () => void;\n /** Sets the state value to a given boolean */\n set: (arg: boolean | (() => boolean)) => void;\n}\n\n/**\n * Hook that stores a boolean value, and provides logic for toggling and setting the value.\n *\n * The return value is a tuple with the value, toggler, and a object with the `true` and `false` setters.\n *\n * @param initialValue - Either the initial value or a function that resolves to it for lazy loading.\n *\n * @returns A tuple with the current state, the state toggler, and a object with `true` and `false` setters.\n *\n * @public\n */\nexport const useToggle = (initialValue: boolean | (() => boolean)): [boolean, TogglerSetter] => {\n const [value, set] = useState(initialValue);\n\n const setTrue = useCallback(() => set(true), [set]);\n const setFalse = useCallback(() => set(false), [set]);\n const toggle = value ? setFalse : setTrue;\n\n return [value, { toggle, setTrue, setFalse, set }];\n};\n"],"names":["useFreezedCallback","callback","reference","useRef","current","useStateObject","initialState","state","set","useState","merge","useCallback","newState","prevState","reset","clear","resolveValue","value","isFunction","asyncFn","args","dependencies","setState","data","loading","error","runAsyncFn","async","useEffect","initialValue","inc","increment","prevValue","dec","decrement","effect","setTrue","setFalse","toggle"],"mappings":"iGAeaA,EAAyBC,IACpC,MAAMC,EAAYC,WAMlB,OAJKD,EAAUE,UACbF,EAAUE,QAAUH,GAGfC,EAAUE,SCCNC,EAAkBC,IAC7B,MAAOC,EAAOC,GAAOC,WAASH,GAExBI,EAAQC,eACXC,GAAqBJ,GAAIK,QAAmBA,KAAcD,OAC3D,CAACJ,IAGGM,EAAQH,eAAY,IAAMH,EAAIF,IAAe,CAACE,EAAKF,IACnDS,EAAQJ,eAAY,IAAMH,EAAI,KAAK,CAACA,IAE1C,MAAO,CAACD,EAAO,CAAEC,IAAAA,EAAKE,MAAAA,EAAOI,MAAAA,EAAOC,MAAAA,KC9BzBC,EAAmBC,GAHN,CAACA,GAAuD,mBAAVA,EAGXC,CAAWD,GAASA,IAAUA,2BCsB3D,CAC9BE,EACAC,EAAkB,GAClBC,EAA0B,MAE1B,MAAOd,EAAOe,GAAYjB,EAAe,CACvCkB,KAAM,KACNC,SAAS,EACTC,MAAO,OAGHC,EAAaf,eAAYgB,UAC7B,IACE,MAAMJ,QAAaJ,KAAWC,GAC9BE,EAASZ,MAAM,CAAEa,KAAAA,EAAMC,SAAS,IAChC,MAAOC,GACPH,EAASZ,MAAM,CAAEe,MAAAA,EAAOD,SAAS,OAElCH,GAMH,OAJAO,aAAU,KACRF,MACCL,GAEId,uBC/BsBU,IAC7B,MAAMf,EAAYC,WAYlB,OAVYH,GAAmB,KACxBE,EAAUE,UACbF,EAAUE,QAAU,CAClBG,MAAOS,EAAaC,KAIjBf,EAAUE,QAAQG,6BCJFsB,IACzB,MAAOZ,EAAOT,GAAOC,WAASoB,GAExBC,EAAMnB,eACV,CAACoB,EAAY,IAAYvB,GAAKwB,GAAsBA,EAAYD,KAChE,CAACvB,IAGGyB,EAAMtB,eACV,CAACuB,EAAY,IAAY1B,GAAKwB,GAAsBA,EAAYE,KAChE,CAAC1B,IAGGM,EAAQH,eAAY,IAAYH,EAAIQ,EAAaa,KAAgB,CAACrB,EAAKqB,IAE7E,MAAO,CAACZ,EAAO,CAAET,IAAAA,EAAKsB,IAAAA,EAAKG,IAAAA,EAAKnB,MAAAA,2BC/BJqB,IAC5BP,YAAUO,EAAQ,6ECiBMN,IACxB,MAAOZ,EAAOT,GAAOC,WAASoB,GAExBO,EAAUzB,eAAY,IAAMH,GAAI,IAAO,CAACA,IACxC6B,EAAW1B,eAAY,IAAMH,GAAI,IAAQ,CAACA,IAGhD,MAAO,CAACS,EAAO,CAAEqB,OAFFrB,EAAQoB,EAAWD,EAETA,QAAAA,EAASC,SAAAA,EAAU7B,IAAAA"} | ||
| {"version":3,"file":"index.cjs.js","sources":["../src/useFreezedCallback/useFreezedCallback.ts","../src/utils.ts","../src/useArray/useArray.ts","../src/useConstant/useConstant.ts","../src/useCounter/useCounter.ts","../src/useEffectOnce/useEffectOnce.ts","../src/useObject/useObject.ts","../src/useToggle/useToggle.ts"],"sourcesContent":["import { useRef } from 'react';\n\n/**\n * Hook that freezed a given callback, so it is only created once in the components life.\n * It ensures the return function is always the same.\n *\n * Useful for optimizations where otherwise constant functions are recalculated every re-render\n *\n * Should the callback ever be recalculated see `React.useCallback` and `React.useMemo`.\n *\n * @public\n * @param callback - The callback to freeze.\n * @returns The freezed callback.\n */\nexport const useFreezedCallback = <T extends (...args: any[]) => any>(\n callback: T,\n): T => {\n const reference = useRef<T>();\n\n if (!reference.current) {\n reference.current = callback;\n }\n\n return reference.current;\n};\n","/** @internal */\nexport const isFunction = (value: unknown): value is Function =>\n typeof value === 'function';\n\n/** @internal */\nexport const resolveValue = <T>(value: T | ((...args: any[]) => T)): T =>\n isFunction(value) ? value() : value;\n","import { useCallback, useState } from 'react';\nimport { resolveValue } from '../utils';\n\n/**\n * @public\n * Setters for the state maintained by `useArray`\n */\nexport interface ArraySetter<T> {\n /** Sets the state, the same you would get with `React.useState`. */\n set: React.Dispatch<React.SetStateAction<T[]>>;\n /** Appends an element to the state */\n append: (element: T) => void;\n /** Prepends an element to the state */\n prepend: (element: T) => void;\n /** Removes and returns the last element from the state */\n pop: () => T;\n /** Removes and returns the first element from the state */\n shift: () => T;\n /** Concatenates a given array to the state */\n concat: (elements: T[]) => void;\n /** Allows you to transform each element of the state, with the same API as `Array.prototype.map` */\n transform: (\n callbackfn: (value: T, index: number, array: T[]) => T,\n thisArg?: any,\n ) => void;\n /** Like `Array.prototype.filter` */\n filter: (\n predicate: (value: T, index: number, array: T[]) => boolean,\n thisArg?: any,\n ) => void;\n /** Resets the state back to the initial value */\n reset: () => void;\n /** Sets the state to `[]` */\n clear: () => void;\n}\n\n/**\n * Hook for creating an array with several setters for ease of use.\n *\n * @public\n * @param initialState - Initial state value\n */\nexport const useArray = <T>(\n initialState: T[] | (() => T[]),\n): [T[], ArraySetter<T>] => {\n const [state, set] = useState(initialState);\n\n const append: ArraySetter<T>['append'] = useCallback(\n (element: T) => set(current => [...current, element]),\n [set],\n );\n\n const prepend: ArraySetter<T>['prepend'] = useCallback(\n (element: T) => set(current => [element, ...current]),\n [set],\n );\n\n const concat: ArraySetter<T>['concat'] = useCallback(\n (elements: T[]) => set(current => [...current, ...elements]),\n [set],\n );\n\n const shift: ArraySetter<T>['shift'] = useCallback(() => {\n let result: T = state[0];\n\n set(([head, ...tail]) => {\n result = head;\n return tail;\n });\n\n return result;\n }, [set, state]);\n\n const pop: ArraySetter<T>['pop'] = useCallback(() => {\n let result: T = state.slice(-1)[0];\n\n set(current => {\n result = current.slice(-1)[0];\n return current.slice(0, -1);\n });\n\n return result;\n }, [set, state]);\n\n const transform: ArraySetter<T>['transform'] = useCallback(\n (callback, thisArg) => {\n set(current => current.map(callback, thisArg));\n },\n [set],\n );\n\n const filter: ArraySetter<T>['filter'] = useCallback(\n (callback, thisArg) => {\n set(current => current.filter(callback, thisArg));\n },\n [set],\n );\n\n const clear: ArraySetter<T>['clear'] = useCallback((): void => set([]), [\n set,\n ]);\n\n const reset: ArraySetter<T>['reset'] = useCallback(\n (): void => set(resolveValue(initialState)),\n [set, initialState],\n );\n\n return [\n state,\n {\n set,\n append,\n prepend,\n pop,\n transform,\n filter,\n shift,\n concat,\n reset,\n clear,\n },\n ];\n};\n","import { useRef } from 'react';\nimport { useFreezedCallback } from '../useFreezedCallback';\nimport { resolveValue } from '../utils';\n\n/**\n * Hook to keep a constant state value.\n * It takes an value or a resolver and maintains a reference to it though re-renders.\n *\n * Returns a getter for state value so it can be lazily set.\n *\n * `React.useState` can be used as an alternative although it should be less performing since it relies on reducers.\n *\n * Should the value change based on dependencies consider `React.useMemo`.\n * Should the value be a reference to a function consider `useFreezedCallback`.\n *\n * @public\n * @param value - Either the state value or its resolver\n * @returns A getter for the state value\n */\nexport const useConstant = <T>(value: T | (() => T)): (() => T) => {\n const reference = useRef<{ state: T }>();\n\n const get = useFreezedCallback(() => {\n if (!reference.current) {\n reference.current = {\n state: resolveValue(value),\n };\n }\n\n return reference.current.state;\n });\n\n return get;\n};\n","import { useState, useCallback } from 'react';\nimport { resolveValue } from '../utils';\n\n/**\n * Signature of the setters provided by `useCounter`\n * @public\n */\nexport interface CounterSetter {\n /** Sets the state to a given value */\n set: (value: number | ((prev: number) => number)) => void;\n /** Increments the state by a given value. Defaults to `1` */\n inc: (value?: number) => void;\n /** Decrements the state by a given value. Defaults to `1` */\n dec: (value?: number) => void;\n /** Resets the state back to its initial value */\n reset: () => void;\n}\n\n/**\n * Simple hook to keep a numeric state with some useful setters.\n *\n * @public\n * @param initialState - Either the initial value or a function that resolves to it for lazy loading.\n * @returns A tuple with the state value, and an object with its setters.\n */\nexport const useCounter = (\n initialState: number | (() => number),\n): [number, CounterSetter] => {\n const [value, set] = useState(initialState);\n\n const inc = useCallback(\n (increment = 1): void => set((currState: number) => currState + increment),\n [set],\n );\n\n const dec = useCallback(\n (decrement = 1): void => set((currState: number) => currState - decrement),\n [set],\n );\n\n const reset = useCallback((): void => set(resolveValue(initialState)), [\n set,\n initialState,\n ]);\n\n return [value, { set, inc, dec, reset }];\n};\n","import { useEffect, EffectCallback } from 'react';\n\n/**\n * This hook its a simple wrapper of `React.useEffect` with and empty dependencies array.\n * It ensures the return function is always the same.\n *\n * @public\n * @param effect - Imperative function that can return a cleanup function.\n */\nexport const useEffectOnce = (effect: EffectCallback): void => {\n useEffect(effect, []); // eslint-disable-line\n};\n","import { useState, useCallback } from 'react';\nimport { resolveValue } from '../utils';\n\n/** Setters of the state maintained by `useObject`\n * @public\n */\nexport interface ObjectSetter<T extends object> {\n /** Merges the current state with the `arg` object. */\n merge: (arg: Partial<T> | ((currState: T) => Partial<T>)) => void;\n /** State setter, the same you would get with `React.useState`. */\n set: React.Dispatch<React.SetStateAction<T>>;\n /** Resets the state back to the initial one. */\n reset: () => void;\n}\n\n/**\n * Hook for creating an object with several setters for ease of use. Like state merging and resetting.\n *\n * @param initialState - Initial state value.\n * @returns A tuple with the current state, and the setters.\n * @public\n */\nexport const useObject = <T extends object>(\n initialState: T,\n): [T, ObjectSetter<T>] => {\n const [state, set] = useState(initialState);\n\n const merge = useCallback(\n (newState: Partial<T> | ((currState: T) => Partial<T>)) =>\n set(currState => ({ ...currState, ...resolveValue(newState) })),\n [set],\n );\n\n const reset = useCallback(() => set(initialState), [set, initialState]);\n\n return [state, { set, merge, reset }];\n};\n","import { useState, useCallback } from 'react';\n\n/** Setters of the state maintained by `useToggle`\n * @public\n */\nexport interface TogglerSetter {\n /** Toggles the state value between `true` and `false` */\n toggle: () => void;\n /** Sets the state value to `true` */\n setTrue: () => void;\n /** Sets the state value to `false` */\n setFalse: () => void;\n /** Sets the state value to a given boolean */\n set: (arg: boolean | (() => boolean)) => void;\n}\n\n/**\n * Hook that stores a boolean value, and provides logic for toggling and setting the value.\n *\n * The return value is a tuple with the value, toggler, and a object with the `true` and `false` setters.\n *\n * @public\n * @param initialValue - Either the initial value or a function that resolves to it for lazy loading.\n * @returns A tuple with the current state, the state toggler, and a object with `true` and `false` setters.\n */\nexport const useToggle = (\n initialValue: boolean | (() => boolean),\n): [boolean, TogglerSetter] => {\n const [value, set] = useState(initialValue);\n\n const setTrue = useCallback(() => set(true), [set]);\n const setFalse = useCallback(() => set(false), [set]);\n const toggle = value ? setFalse : setTrue;\n\n return [value, { toggle, setTrue, setFalse, set }];\n};\n"],"names":["useFreezedCallback","callback","reference","useRef","current","resolveValue","value","isFunction","initialState","state","set","useState","append","useCallback","element","prepend","concat","elements","shift","result","head","tail","pop","slice","transform","thisArg","map","filter","clear","reset","inc","increment","currState","dec","decrement","effect","useEffect","merge","newState","initialValue","setTrue","setFalse","toggle"],"mappings":"iGAcaA,EACXC,IAEA,MAAMC,EAAYC,WAMlB,OAJKD,EAAUE,UACbF,EAAUE,QAAUH,GAGfC,EAAUE,SClBNC,EAAmBC,GAJN,CAACA,GACR,mBAAVA,EAIPC,CAAWD,GAASA,IAAUA,mBCqC9BE,IAEA,MAAOC,EAAOC,GAAOC,WAASH,GAExBI,EAAmCC,eACtCC,GAAeJ,GAAIN,GAAW,IAAIA,EAASU,MAC5C,CAACJ,IAGGK,EAAqCF,eACxCC,GAAeJ,GAAIN,GAAW,CAACU,KAAYV,MAC5C,CAACM,IAGGM,EAAmCH,eACtCI,GAAkBP,GAAIN,GAAW,IAAIA,KAAYa,MAClD,CAACP,IAGGQ,EAAiCL,eAAY,KACjD,IAAIM,EAAYV,EAAM,GAOtB,OALAC,GAAI,EAAEU,KAASC,MACbF,EAASC,EACFC,KAGFF,IACN,CAACT,EAAKD,IAEHa,EAA6BT,eAAY,KAC7C,IAAIM,EAAYV,EAAMc,OAAO,GAAG,GAOhC,OALAb,GAAIN,IACFe,EAASf,EAAQmB,OAAO,GAAG,GACpBnB,EAAQmB,MAAM,GAAI,MAGpBJ,IACN,CAACT,EAAKD,IAEHe,EAAyCX,eAC7C,CAACZ,EAAUwB,KACTf,GAAIN,GAAWA,EAAQsB,IAAIzB,EAAUwB,OAEvC,CAACf,IAGGiB,EAAmCd,eACvC,CAACZ,EAAUwB,KACTf,GAAIN,GAAWA,EAAQuB,OAAO1B,EAAUwB,OAE1C,CAACf,IAGGkB,EAAiCf,eAAY,IAAYH,EAAI,KAAK,CACtEA,IAGImB,EAAiChB,eACrC,IAAYH,EAAIL,EAAaG,KAC7B,CAACE,EAAKF,IAGR,MAAO,CACLC,EACA,CACEC,IAAAA,EACAE,OAAAA,EACAG,QAAAA,EACAO,IAAAA,EACAE,UAAAA,EACAG,OAAAA,EACAT,MAAAA,EACAF,OAAAA,EACAa,MAAAA,EACAD,MAAAA,yBCpGyBtB,IAC7B,MAAMJ,EAAYC,WAYlB,OAVYH,GAAmB,KACxBE,EAAUE,UACbF,EAAUE,QAAU,CAClBK,MAAOJ,EAAaC,KAIjBJ,EAAUE,QAAQK,6BCH3BD,IAEA,MAAOF,EAAOI,GAAOC,WAASH,GAExBsB,EAAMjB,eACV,CAACkB,EAAY,IAAYrB,GAAKsB,GAAsBA,EAAYD,KAChE,CAACrB,IAGGuB,EAAMpB,eACV,CAACqB,EAAY,IAAYxB,GAAKsB,GAAsBA,EAAYE,KAChE,CAACxB,IAGGmB,EAAQhB,eAAY,IAAYH,EAAIL,EAAaG,KAAgB,CACrEE,EACAF,IAGF,MAAO,CAACF,EAAO,CAAEI,IAAAA,EAAKoB,IAAAA,EAAKG,IAAAA,EAAKJ,MAAAA,2BCpCJM,IAC5BC,YAAUD,EAAQ,oDCalB3B,IAEA,MAAOC,EAAOC,GAAOC,WAASH,GAExB6B,EAAQxB,eACXyB,GACC5B,GAAIsB,QAAmBA,KAAc3B,EAAaiC,QACpD,CAAC5B,IAGGmB,EAAQhB,eAAY,IAAMH,EAAIF,IAAe,CAACE,EAAKF,IAEzD,MAAO,CAACC,EAAO,CAAEC,IAAAA,EAAK2B,MAAAA,EAAOR,MAAAA,uBCT7BU,IAEA,MAAOjC,EAAOI,GAAOC,WAAS4B,GAExBC,EAAU3B,eAAY,IAAMH,GAAI,IAAO,CAACA,IACxC+B,EAAW5B,eAAY,IAAMH,GAAI,IAAQ,CAACA,IAGhD,MAAO,CAACJ,EAAO,CAAEoC,OAFFpC,EAAQmC,EAAWD,EAETA,QAAAA,EAASC,SAAAA,EAAU/B,IAAAA"} |
@@ -1,2 +0,2 @@ | ||
| import{useRef as r,useEffect as t,useState as e,useCallback as n}from"react";const c=t=>{const e=r();return e.current||(e.current=t),e.current},o=r=>{t(r,[])},s=r=>{const[t,c]=e(r),o=n((r=>c((t=>({...t,...r})))),[c]),s=n((()=>c(r)),[c,r]),a=n((()=>c({})),[c]);return[t,{set:c,merge:o,reset:s,clear:a}]},a=(r,e=[],c=[])=>{const[o,a]=s({data:null,loading:!0,error:null}),u=n((async()=>{try{const t=await r(...e);a.merge({data:t,loading:!1})}catch(r){a.merge({error:r,loading:!1})}}),c);return t((()=>{u()}),c),o},u=r=>{const[t,c]=e(r),o=n((()=>c(!0)),[c]),s=n((()=>c(!1)),[c]);return[t,{toggle:t?s:o,setTrue:o,setFalse:s,set:c}]},l=r=>(r=>"function"==typeof r)(r)?r():r,g=r=>{const[t,c]=e(r),o=n(((r=1)=>c((t=>t+r))),[c]),s=n(((r=1)=>c((t=>t-r))),[c]),a=n((()=>c(l(r))),[c,r]);return[t,{set:c,inc:o,dec:s,reset:a}]},i=t=>{const e=r();return c((()=>(e.current||(e.current={state:l(t)}),e.current.state)))};export{a as useAsyncFunction,i as useConstant,g as useCounter,o as useEffectOnce,c as useFreezedCallback,s as useStateObject,u as useToggle}; | ||
| import{useRef as e,useEffect as t,useState as r,useCallback as n}from"react";const s=t=>{const r=e();return r.current||(r.current=t),r.current},c=e=>{t(e,[])},o=e=>(e=>"function"==typeof e)(e)?e():e,u=e=>{const[t,s]=r(e),c=n((e=>s((t=>({...t,...o(e)})))),[s]),u=n((()=>s(e)),[s,e]);return[t,{set:s,merge:c,reset:u}]},l=e=>{const[t,s]=r(e),c=n((()=>s(!0)),[s]),o=n((()=>s(!1)),[s]);return[t,{toggle:t?o:c,setTrue:c,setFalse:o,set:s}]},p=e=>{const[t,s]=r(e),c=n(((e=1)=>s((t=>t+e))),[s]),u=n(((e=1)=>s((t=>t-e))),[s]),l=n((()=>s(o(e))),[s,e]);return[t,{set:s,inc:c,dec:u,reset:l}]},a=t=>{const r=e();return s((()=>(r.current||(r.current={state:o(t)}),r.current.state)))},i=e=>{const[t,s]=r(e),c=n((e=>s((t=>[...t,e]))),[s]),u=n((e=>s((t=>[e,...t]))),[s]),l=n((e=>s((t=>[...t,...e]))),[s]),p=n((()=>{let e=t[0];return s((([t,...r])=>(e=t,r))),e}),[s,t]),a=n((()=>{let e=t.slice(-1)[0];return s((t=>(e=t.slice(-1)[0],t.slice(0,-1)))),e}),[s,t]),i=n(((e,t)=>{s((r=>r.map(e,t)))}),[s]),f=n(((e,t)=>{s((r=>r.filter(e,t)))}),[s]),m=n((()=>s([])),[s]),d=n((()=>s(o(e))),[s,e]);return[t,{set:s,append:c,prepend:u,pop:a,transform:i,filter:f,shift:p,concat:l,reset:d,clear:m}]};export{i as useArray,a as useConstant,p as useCounter,c as useEffectOnce,s as useFreezedCallback,u as useObject,l as useToggle}; | ||
| //# sourceMappingURL=index.esm.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.esm.js","sources":["../src/useFreezedCallback/useFreezedCallback.ts","../src/useEffectOnce/useEffectOnce.ts","../src/useStateObject/useStateObject.ts","../src/useAsyncFunction/useAsyncFunction.ts","../src/useToggle/useToggle.ts","../src/utils.ts","../src/useCounter/useCounter.ts","../src/useConstant/useConstant.ts"],"sourcesContent":["import { useRef } from 'react';\nimport { GenericFunction } from '../types';\n\n/**\n * Hook that freezed a given callback, so it is only created once in the components life.\n * It ensures the return function is always the same.\n *\n * Useful for optimizations where otherwise constant functions are recalculated every re-render\n *\n * Should the callback ever be recalculated see `React.useCallback` and `React.useMemo`.\n *\n * @param callback - The callback to freeze.\n * @returns The freezed callback.\n * @public\n */\nexport const useFreezedCallback = <T>(callback: GenericFunction<T>): GenericFunction<T> => {\n const reference = useRef<GenericFunction<T>>();\n\n if (!reference.current) {\n reference.current = callback;\n }\n\n return reference.current;\n};\n","import { useEffect, EffectCallback } from 'react';\n\n/**\n * This hook its a simple wrapper of `React.useEffect` with and empty dependencies array.\n * It ensures the return function is always the same.\n *\n * @param effect - Imperative function that can return a cleanup function.\n * @public\n */\nexport const useEffectOnce = (effect: EffectCallback): void => {\n useEffect(effect, []); // eslint-disable-line\n};\n","import { useState, useCallback } from 'react';\n\n/** Setters of the state maintained by `useStateObject`\n * @public\n */\nexport interface StateObjectSetter {\n /** Merges the current state with the `arg` object. */\n merge: (arg: object) => void;\n /** State setter, the same you would get with `React.useState`. */\n set: (arg: object | ((prevState: object) => object)) => void;\n /** Resets the state back to the initial one. */\n reset: () => void;\n /** Sets the state to an empty object (`{}`). */\n clear: () => void;\n}\n\n/**\n * Hook for creating an object with several setters for ease of use. Like state merging and resetting.\n *\n * @param initialState - Initial state value.\n * @returns A tuple with the current state, and the setters.\n * @public\n */\nexport const useStateObject = (initialState: object): [object, StateObjectSetter] => {\n const [state, set] = useState(initialState);\n\n const merge = useCallback(\n (newState: object) => set(prevState => ({ ...prevState, ...newState })),\n [set],\n );\n\n const reset = useCallback(() => set(initialState), [set, initialState]);\n const clear = useCallback(() => set({}), [set]);\n\n return [state, { set, merge, reset, clear }];\n};\n","import { useEffect, useCallback } from 'react';\nimport { useStateObject } from '../useStateObject';\n\nimport { AsyncFunction } from '../types';\n\n/**\n * @public\n */\nexport interface AsyncFunctionState<T> {\n data: T;\n loading: boolean;\n error: unknown;\n}\n\n/**\n * Useful hook for running side effects and monitor their current state.\n * `loading` flag is initialized to `true` and changes to `false` once `asyncFn` has returned.\n *\n * @param asyncFn - Async function that will be run .\n * @param args - Array of arguments for that `asyncFn` takes.\n * @param dependencies - `asyncFn` will run each time the values of this array change.\n *\n *\n * @returns Object holding the current status (`loading`) and either the resulting data or an error.\n * @public\n */\nexport const useAsyncFunction = <T>(\n asyncFn: AsyncFunction<T>,\n args: unknown[] = [],\n dependencies: unknown[] = [],\n): AsyncFunctionState<T> => {\n const [state, setState] = useStateObject({\n data: null,\n loading: true,\n error: null,\n });\n\n const runAsyncFn = useCallback(async () => {\n try {\n const data = await asyncFn(...args);\n setState.merge({ data, loading: false });\n } catch (error) {\n setState.merge({ error, loading: false });\n }\n }, dependencies); // eslint-disable-line\n\n useEffect(() => {\n runAsyncFn();\n }, dependencies); // eslint-disable-line\n\n return state as AsyncFunctionState<T>;\n};\n","import { useState, useCallback } from 'react';\n\n/** Setters of the state maintained by `useToggle`\n * @public\n */\nexport interface TogglerSetter {\n /** Toggles the state value between `true` and `false` */\n toggle: () => void;\n /** Sets the state value to `true` */\n setTrue: () => void;\n /** Sets the state value to `false` */\n setFalse: () => void;\n /** Sets the state value to a given boolean */\n set: (arg: boolean | (() => boolean)) => void;\n}\n\n/**\n * Hook that stores a boolean value, and provides logic for toggling and setting the value.\n *\n * The return value is a tuple with the value, toggler, and a object with the `true` and `false` setters.\n *\n * @param initialValue - Either the initial value or a function that resolves to it for lazy loading.\n *\n * @returns A tuple with the current state, the state toggler, and a object with `true` and `false` setters.\n *\n * @public\n */\nexport const useToggle = (initialValue: boolean | (() => boolean)): [boolean, TogglerSetter] => {\n const [value, set] = useState(initialValue);\n\n const setTrue = useCallback(() => set(true), [set]);\n const setFalse = useCallback(() => set(false), [set]);\n const toggle = value ? setFalse : setTrue;\n\n return [value, { toggle, setTrue, setFalse, set }];\n};\n","/** @internal */\nexport const isFunction = (value: unknown): value is Function => typeof value === 'function';\n\n/** @internal */\nexport const resolveValue = <T>(value: T | (() => T)): T => (isFunction(value) ? value() : value);\n","import { useState, useCallback } from 'react';\nimport { resolveValue } from '../utils';\n\n/**\n * Signature of the setters provided by `useCounter`\n * @public\n */\nexport interface CounterSetter {\n /** Sets the state to a given value */\n set: (value: number | ((prev: number) => number)) => void;\n /** Increments the state by a given value. Defaults to `1` */\n inc: (value?: number) => void;\n /** Decrements the state by a given value. Defaults to `1` */\n dec: (value?: number) => void;\n /** Resets the state back to its initial value */\n reset: () => void;\n}\n\n/**\n * Simple hook to keep a numeric state with some useful setters.\n *\n * @param initialValue - Either the initial value or a function that resolves to it for lazy loading.\n * @returns A tuple with the state value, and an object with its setters.\n * @public\n */\nexport const useCounter = (initialValue: number | (() => number)): [number, CounterSetter] => {\n const [value, set] = useState(initialValue);\n\n const inc = useCallback(\n (increment = 1): void => set((prevValue: number) => prevValue + increment),\n [set],\n );\n\n const dec = useCallback(\n (decrement = 1): void => set((prevValue: number) => prevValue - decrement),\n [set],\n );\n\n const reset = useCallback((): void => set(resolveValue(initialValue)), [set, initialValue]);\n\n return [value, { set, inc, dec, reset }];\n};\n","import { useRef } from 'react';\nimport { useFreezedCallback } from '../useFreezedCallback';\nimport { resolveValue } from '../utils';\n\n/**\n * Hook to keep a constant state value.\n * It takes an value or a resolver and maintains a reference to it though re-renders.\n *\n * Returns a getter for state value so it can be lazily set.\n *\n * `React.useState` can be used as an alternative although it should be less performing since it relies on reducers.\n *\n * Should the value change based on dependencies consider `React.useMemo`.\n * Should the value be a reference to a function consider `useFreezedCallback`.\n *\n * @param value - Either the state value or its resolver\n * @returns A getter for the state value\n * @public\n */\nexport const useConstant = <T>(value: T | (() => T)): (() => T) => {\n const reference = useRef<{ state: T }>();\n\n const get = useFreezedCallback(() => {\n if (!reference.current) {\n reference.current = {\n state: resolveValue(value),\n };\n }\n\n return reference.current.state;\n });\n\n return get;\n};\n"],"names":["useFreezedCallback","callback","reference","useRef","current","useEffectOnce","effect","useEffect","useStateObject","initialState","state","set","useState","merge","useCallback","newState","prevState","reset","clear","useAsyncFunction","asyncFn","args","dependencies","setState","data","loading","error","runAsyncFn","async","useToggle","initialValue","value","setTrue","setFalse","toggle","resolveValue","isFunction","useCounter","inc","increment","prevValue","dec","decrement","useConstant"],"mappings":"mFAeaA,EAAyBC,IACpC,MAAMC,EAAYC,IAMlB,OAJKD,EAAUE,UACbF,EAAUE,QAAUH,GAGfC,EAAUE,SCbNC,EAAiBC,IAC5BC,EAAUD,EAAQ,KCaPE,EAAkBC,IAC7B,MAAOC,EAAOC,GAAOC,EAASH,GAExBI,EAAQC,GACXC,GAAqBJ,GAAIK,QAAmBA,KAAcD,OAC3D,CAACJ,IAGGM,EAAQH,GAAY,IAAMH,EAAIF,IAAe,CAACE,EAAKF,IACnDS,EAAQJ,GAAY,IAAMH,EAAI,KAAK,CAACA,IAE1C,MAAO,CAACD,EAAO,CAAEC,IAAAA,EAAKE,MAAAA,EAAOI,MAAAA,EAAOC,MAAAA,KCRzBC,EAAmB,CAC9BC,EACAC,EAAkB,GAClBC,EAA0B,MAE1B,MAAOZ,EAAOa,GAAYf,EAAe,CACvCgB,KAAM,KACNC,SAAS,EACTC,MAAO,OAGHC,EAAab,GAAYc,UAC7B,IACE,MAAMJ,QAAaJ,KAAWC,GAC9BE,EAASV,MAAM,CAAEW,KAAAA,EAAMC,SAAS,IAChC,MAAOC,GACPH,EAASV,MAAM,CAAEa,MAAAA,EAAOD,SAAS,OAElCH,GAMH,OAJAf,GAAU,KACRoB,MACCL,GAEIZ,GCvBImB,EAAaC,IACxB,MAAOC,EAAOpB,GAAOC,EAASkB,GAExBE,EAAUlB,GAAY,IAAMH,GAAI,IAAO,CAACA,IACxCsB,EAAWnB,GAAY,IAAMH,GAAI,IAAQ,CAACA,IAGhD,MAAO,CAACoB,EAAO,CAAEG,OAFFH,EAAQE,EAAWD,EAETA,QAAAA,EAASC,SAAAA,EAAUtB,IAAAA,KC9BjCwB,EAAmBJ,GAHN,CAACA,GAAuD,mBAAVA,EAGXK,CAAWL,GAASA,IAAUA,ECqB9EM,EAAcP,IACzB,MAAOC,EAAOpB,GAAOC,EAASkB,GAExBQ,EAAMxB,GACV,CAACyB,EAAY,IAAY5B,GAAK6B,GAAsBA,EAAYD,KAChE,CAAC5B,IAGG8B,EAAM3B,GACV,CAAC4B,EAAY,IAAY/B,GAAK6B,GAAsBA,EAAYE,KAChE,CAAC/B,IAGGM,EAAQH,GAAY,IAAYH,EAAIwB,EAAaL,KAAgB,CAACnB,EAAKmB,IAE7E,MAAO,CAACC,EAAO,CAAEpB,IAAAA,EAAK2B,IAAAA,EAAKG,IAAAA,EAAKxB,MAAAA,KCrBrB0B,EAAkBZ,IAC7B,MAAM7B,EAAYC,IAYlB,OAVYH,GAAmB,KACxBE,EAAUE,UACbF,EAAUE,QAAU,CAClBM,MAAOyB,EAAaJ,KAIjB7B,EAAUE,QAAQM"} | ||
| {"version":3,"file":"index.esm.js","sources":["../src/useFreezedCallback/useFreezedCallback.ts","../src/useEffectOnce/useEffectOnce.ts","../src/utils.ts","../src/useObject/useObject.ts","../src/useToggle/useToggle.ts","../src/useCounter/useCounter.ts","../src/useConstant/useConstant.ts","../src/useArray/useArray.ts"],"sourcesContent":["import { useRef } from 'react';\n\n/**\n * Hook that freezed a given callback, so it is only created once in the components life.\n * It ensures the return function is always the same.\n *\n * Useful for optimizations where otherwise constant functions are recalculated every re-render\n *\n * Should the callback ever be recalculated see `React.useCallback` and `React.useMemo`.\n *\n * @public\n * @param callback - The callback to freeze.\n * @returns The freezed callback.\n */\nexport const useFreezedCallback = <T extends (...args: any[]) => any>(\n callback: T,\n): T => {\n const reference = useRef<T>();\n\n if (!reference.current) {\n reference.current = callback;\n }\n\n return reference.current;\n};\n","import { useEffect, EffectCallback } from 'react';\n\n/**\n * This hook its a simple wrapper of `React.useEffect` with and empty dependencies array.\n * It ensures the return function is always the same.\n *\n * @public\n * @param effect - Imperative function that can return a cleanup function.\n */\nexport const useEffectOnce = (effect: EffectCallback): void => {\n useEffect(effect, []); // eslint-disable-line\n};\n","/** @internal */\nexport const isFunction = (value: unknown): value is Function =>\n typeof value === 'function';\n\n/** @internal */\nexport const resolveValue = <T>(value: T | ((...args: any[]) => T)): T =>\n isFunction(value) ? value() : value;\n","import { useState, useCallback } from 'react';\nimport { resolveValue } from '../utils';\n\n/** Setters of the state maintained by `useObject`\n * @public\n */\nexport interface ObjectSetter<T extends object> {\n /** Merges the current state with the `arg` object. */\n merge: (arg: Partial<T> | ((currState: T) => Partial<T>)) => void;\n /** State setter, the same you would get with `React.useState`. */\n set: React.Dispatch<React.SetStateAction<T>>;\n /** Resets the state back to the initial one. */\n reset: () => void;\n}\n\n/**\n * Hook for creating an object with several setters for ease of use. Like state merging and resetting.\n *\n * @param initialState - Initial state value.\n * @returns A tuple with the current state, and the setters.\n * @public\n */\nexport const useObject = <T extends object>(\n initialState: T,\n): [T, ObjectSetter<T>] => {\n const [state, set] = useState(initialState);\n\n const merge = useCallback(\n (newState: Partial<T> | ((currState: T) => Partial<T>)) =>\n set(currState => ({ ...currState, ...resolveValue(newState) })),\n [set],\n );\n\n const reset = useCallback(() => set(initialState), [set, initialState]);\n\n return [state, { set, merge, reset }];\n};\n","import { useState, useCallback } from 'react';\n\n/** Setters of the state maintained by `useToggle`\n * @public\n */\nexport interface TogglerSetter {\n /** Toggles the state value between `true` and `false` */\n toggle: () => void;\n /** Sets the state value to `true` */\n setTrue: () => void;\n /** Sets the state value to `false` */\n setFalse: () => void;\n /** Sets the state value to a given boolean */\n set: (arg: boolean | (() => boolean)) => void;\n}\n\n/**\n * Hook that stores a boolean value, and provides logic for toggling and setting the value.\n *\n * The return value is a tuple with the value, toggler, and a object with the `true` and `false` setters.\n *\n * @public\n * @param initialValue - Either the initial value or a function that resolves to it for lazy loading.\n * @returns A tuple with the current state, the state toggler, and a object with `true` and `false` setters.\n */\nexport const useToggle = (\n initialValue: boolean | (() => boolean),\n): [boolean, TogglerSetter] => {\n const [value, set] = useState(initialValue);\n\n const setTrue = useCallback(() => set(true), [set]);\n const setFalse = useCallback(() => set(false), [set]);\n const toggle = value ? setFalse : setTrue;\n\n return [value, { toggle, setTrue, setFalse, set }];\n};\n","import { useState, useCallback } from 'react';\nimport { resolveValue } from '../utils';\n\n/**\n * Signature of the setters provided by `useCounter`\n * @public\n */\nexport interface CounterSetter {\n /** Sets the state to a given value */\n set: (value: number | ((prev: number) => number)) => void;\n /** Increments the state by a given value. Defaults to `1` */\n inc: (value?: number) => void;\n /** Decrements the state by a given value. Defaults to `1` */\n dec: (value?: number) => void;\n /** Resets the state back to its initial value */\n reset: () => void;\n}\n\n/**\n * Simple hook to keep a numeric state with some useful setters.\n *\n * @public\n * @param initialState - Either the initial value or a function that resolves to it for lazy loading.\n * @returns A tuple with the state value, and an object with its setters.\n */\nexport const useCounter = (\n initialState: number | (() => number),\n): [number, CounterSetter] => {\n const [value, set] = useState(initialState);\n\n const inc = useCallback(\n (increment = 1): void => set((currState: number) => currState + increment),\n [set],\n );\n\n const dec = useCallback(\n (decrement = 1): void => set((currState: number) => currState - decrement),\n [set],\n );\n\n const reset = useCallback((): void => set(resolveValue(initialState)), [\n set,\n initialState,\n ]);\n\n return [value, { set, inc, dec, reset }];\n};\n","import { useRef } from 'react';\nimport { useFreezedCallback } from '../useFreezedCallback';\nimport { resolveValue } from '../utils';\n\n/**\n * Hook to keep a constant state value.\n * It takes an value or a resolver and maintains a reference to it though re-renders.\n *\n * Returns a getter for state value so it can be lazily set.\n *\n * `React.useState` can be used as an alternative although it should be less performing since it relies on reducers.\n *\n * Should the value change based on dependencies consider `React.useMemo`.\n * Should the value be a reference to a function consider `useFreezedCallback`.\n *\n * @public\n * @param value - Either the state value or its resolver\n * @returns A getter for the state value\n */\nexport const useConstant = <T>(value: T | (() => T)): (() => T) => {\n const reference = useRef<{ state: T }>();\n\n const get = useFreezedCallback(() => {\n if (!reference.current) {\n reference.current = {\n state: resolveValue(value),\n };\n }\n\n return reference.current.state;\n });\n\n return get;\n};\n","import { useCallback, useState } from 'react';\nimport { resolveValue } from '../utils';\n\n/**\n * @public\n * Setters for the state maintained by `useArray`\n */\nexport interface ArraySetter<T> {\n /** Sets the state, the same you would get with `React.useState`. */\n set: React.Dispatch<React.SetStateAction<T[]>>;\n /** Appends an element to the state */\n append: (element: T) => void;\n /** Prepends an element to the state */\n prepend: (element: T) => void;\n /** Removes and returns the last element from the state */\n pop: () => T;\n /** Removes and returns the first element from the state */\n shift: () => T;\n /** Concatenates a given array to the state */\n concat: (elements: T[]) => void;\n /** Allows you to transform each element of the state, with the same API as `Array.prototype.map` */\n transform: (\n callbackfn: (value: T, index: number, array: T[]) => T,\n thisArg?: any,\n ) => void;\n /** Like `Array.prototype.filter` */\n filter: (\n predicate: (value: T, index: number, array: T[]) => boolean,\n thisArg?: any,\n ) => void;\n /** Resets the state back to the initial value */\n reset: () => void;\n /** Sets the state to `[]` */\n clear: () => void;\n}\n\n/**\n * Hook for creating an array with several setters for ease of use.\n *\n * @public\n * @param initialState - Initial state value\n */\nexport const useArray = <T>(\n initialState: T[] | (() => T[]),\n): [T[], ArraySetter<T>] => {\n const [state, set] = useState(initialState);\n\n const append: ArraySetter<T>['append'] = useCallback(\n (element: T) => set(current => [...current, element]),\n [set],\n );\n\n const prepend: ArraySetter<T>['prepend'] = useCallback(\n (element: T) => set(current => [element, ...current]),\n [set],\n );\n\n const concat: ArraySetter<T>['concat'] = useCallback(\n (elements: T[]) => set(current => [...current, ...elements]),\n [set],\n );\n\n const shift: ArraySetter<T>['shift'] = useCallback(() => {\n let result: T = state[0];\n\n set(([head, ...tail]) => {\n result = head;\n return tail;\n });\n\n return result;\n }, [set, state]);\n\n const pop: ArraySetter<T>['pop'] = useCallback(() => {\n let result: T = state.slice(-1)[0];\n\n set(current => {\n result = current.slice(-1)[0];\n return current.slice(0, -1);\n });\n\n return result;\n }, [set, state]);\n\n const transform: ArraySetter<T>['transform'] = useCallback(\n (callback, thisArg) => {\n set(current => current.map(callback, thisArg));\n },\n [set],\n );\n\n const filter: ArraySetter<T>['filter'] = useCallback(\n (callback, thisArg) => {\n set(current => current.filter(callback, thisArg));\n },\n [set],\n );\n\n const clear: ArraySetter<T>['clear'] = useCallback((): void => set([]), [\n set,\n ]);\n\n const reset: ArraySetter<T>['reset'] = useCallback(\n (): void => set(resolveValue(initialState)),\n [set, initialState],\n );\n\n return [\n state,\n {\n set,\n append,\n prepend,\n pop,\n transform,\n filter,\n shift,\n concat,\n reset,\n clear,\n },\n ];\n};\n"],"names":["useFreezedCallback","callback","reference","useRef","current","useEffectOnce","effect","useEffect","resolveValue","value","isFunction","useObject","initialState","state","set","useState","merge","useCallback","newState","currState","reset","useToggle","initialValue","setTrue","setFalse","toggle","useCounter","inc","increment","dec","decrement","useConstant","useArray","append","element","prepend","concat","elements","shift","result","head","tail","pop","slice","transform","thisArg","map","filter","clear"],"mappings":"mFAcaA,EACXC,IAEA,MAAMC,EAAYC,IAMlB,OAJKD,EAAUE,UACbF,EAAUE,QAAUH,GAGfC,EAAUE,SCdNC,EAAiBC,IAC5BC,EAAUD,EAAQ,KCLPE,EAAmBC,GAJN,CAACA,GACR,mBAAVA,EAIPC,CAAWD,GAASA,IAAUA,ECgBnBE,EACXC,IAEA,MAAOC,EAAOC,GAAOC,EAASH,GAExBI,EAAQC,GACXC,GACCJ,GAAIK,QAAmBA,KAAcX,EAAaU,QACpD,CAACJ,IAGGM,EAAQH,GAAY,IAAMH,EAAIF,IAAe,CAACE,EAAKF,IAEzD,MAAO,CAACC,EAAO,CAAEC,IAAAA,EAAKE,MAAAA,EAAOI,MAAAA,KCVlBC,EACXC,IAEA,MAAOb,EAAOK,GAAOC,EAASO,GAExBC,EAAUN,GAAY,IAAMH,GAAI,IAAO,CAACA,IACxCU,EAAWP,GAAY,IAAMH,GAAI,IAAQ,CAACA,IAGhD,MAAO,CAACL,EAAO,CAAEgB,OAFFhB,EAAQe,EAAWD,EAETA,QAAAA,EAASC,SAAAA,EAAUV,IAAAA,KCTjCY,EACXd,IAEA,MAAOH,EAAOK,GAAOC,EAASH,GAExBe,EAAMV,GACV,CAACW,EAAY,IAAYd,GAAKK,GAAsBA,EAAYS,KAChE,CAACd,IAGGe,EAAMZ,GACV,CAACa,EAAY,IAAYhB,GAAKK,GAAsBA,EAAYW,KAChE,CAAChB,IAGGM,EAAQH,GAAY,IAAYH,EAAIN,EAAaI,KAAgB,CACrEE,EACAF,IAGF,MAAO,CAACH,EAAO,CAAEK,IAAAA,EAAKa,IAAAA,EAAKE,IAAAA,EAAKT,MAAAA,KC1BrBW,EAAkBtB,IAC7B,MAAMP,EAAYC,IAYlB,OAVYH,GAAmB,KACxBE,EAAUE,UACbF,EAAUE,QAAU,CAClBS,MAAOL,EAAaC,KAIjBP,EAAUE,QAAQS,UCahBmB,EACXpB,IAEA,MAAOC,EAAOC,GAAOC,EAASH,GAExBqB,EAAmChB,GACtCiB,GAAepB,GAAIV,GAAW,IAAIA,EAAS8B,MAC5C,CAACpB,IAGGqB,EAAqClB,GACxCiB,GAAepB,GAAIV,GAAW,CAAC8B,KAAY9B,MAC5C,CAACU,IAGGsB,EAAmCnB,GACtCoB,GAAkBvB,GAAIV,GAAW,IAAIA,KAAYiC,MAClD,CAACvB,IAGGwB,EAAiCrB,GAAY,KACjD,IAAIsB,EAAY1B,EAAM,GAOtB,OALAC,GAAI,EAAE0B,KAASC,MACbF,EAASC,EACFC,KAGFF,IACN,CAACzB,EAAKD,IAEH6B,EAA6BzB,GAAY,KAC7C,IAAIsB,EAAY1B,EAAM8B,OAAO,GAAG,GAOhC,OALA7B,GAAIV,IACFmC,EAASnC,EAAQuC,OAAO,GAAG,GACpBvC,EAAQuC,MAAM,GAAI,MAGpBJ,IACN,CAACzB,EAAKD,IAEH+B,EAAyC3B,GAC7C,CAAChB,EAAU4C,KACT/B,GAAIV,GAAWA,EAAQ0C,IAAI7C,EAAU4C,OAEvC,CAAC/B,IAGGiC,EAAmC9B,GACvC,CAAChB,EAAU4C,KACT/B,GAAIV,GAAWA,EAAQ2C,OAAO9C,EAAU4C,OAE1C,CAAC/B,IAGGkC,EAAiC/B,GAAY,IAAYH,EAAI,KAAK,CACtEA,IAGIM,EAAiCH,GACrC,IAAYH,EAAIN,EAAaI,KAC7B,CAACE,EAAKF,IAGR,MAAO,CACLC,EACA,CACEC,IAAAA,EACAmB,OAAAA,EACAE,QAAAA,EACAO,IAAAA,EACAE,UAAAA,EACAG,OAAAA,EACAT,MAAAA,EACAF,OAAAA,EACAhB,MAAAA,EACA4B,MAAAA"} |
+43
-39
@@ -0,16 +1,35 @@ | ||
| /// <reference types="react" /> | ||
| import { EffectCallback } from 'react'; | ||
| /** Generic asynchronous function | ||
| /** | ||
| * @public | ||
| * Setters for the state maintained by `useArray` | ||
| */ | ||
| export declare type AsyncFunction<T> = (...args: any[]) => Promise<T>; | ||
| export declare interface ArraySetter<T> { | ||
| /** Sets the state, the same you would get with `React.useState`. */ | ||
| set: React.Dispatch<React.SetStateAction<T[]>>; | ||
| /** Appends an element to the state */ | ||
| append: (element: T) => void; | ||
| /** Prepends an element to the state */ | ||
| prepend: (element: T) => void; | ||
| /** Removes and returns the last element from the state */ | ||
| pop: () => T; | ||
| /** Removes and returns the first element from the state */ | ||
| shift: () => T; | ||
| /** Concatenates a given array to the state */ | ||
| concat: (elements: T[]) => void; | ||
| /** Allows you to transform each element of the state, with the same API as `Array.prototype.map` */ | ||
| transform: (callbackfn: (value: T, index: number, array: T[]) => T, thisArg?: any) => void; | ||
| /** Like `Array.prototype.filter` */ | ||
| filter: (predicate: (value: T, index: number, array: T[]) => boolean, thisArg?: any) => void; | ||
| /** Resets the state back to the initial value */ | ||
| reset: () => void; | ||
| /** Sets the state to `[]` */ | ||
| clear: () => void; | ||
| } | ||
| /** | ||
| /** Generic asynchronous function | ||
| * @public | ||
| */ | ||
| export declare interface AsyncFunctionState<T> { | ||
| data: T; | ||
| loading: boolean; | ||
| error: unknown; | ||
| } | ||
| export declare type AsyncFunction<T> = (...args: any[]) => Promise<T>; | ||
@@ -32,19 +51,12 @@ /** | ||
| /** Function with generic parameters and return value | ||
| /** Setters of the state maintained by `useObject` | ||
| * @public | ||
| */ | ||
| export declare type GenericFunction<T> = (...args: any[]) => T; | ||
| /** Setters of the state maintained by `useStateObject` | ||
| * @public | ||
| */ | ||
| export declare interface StateObjectSetter { | ||
| export declare interface ObjectSetter<T extends object> { | ||
| /** Merges the current state with the `arg` object. */ | ||
| merge: (arg: object) => void; | ||
| merge: (arg: Partial<T> | ((currState: T) => Partial<T>)) => void; | ||
| /** State setter, the same you would get with `React.useState`. */ | ||
| set: (arg: object | ((prevState: object) => object)) => void; | ||
| set: React.Dispatch<React.SetStateAction<T>>; | ||
| /** Resets the state back to the initial one. */ | ||
| reset: () => void; | ||
| /** Sets the state to an empty object (`{}`). */ | ||
| clear: () => void; | ||
| } | ||
@@ -67,14 +79,8 @@ | ||
| /** | ||
| * Useful hook for running side effects and monitor their current state. | ||
| * `loading` flag is initialized to `true` and changes to `false` once `asyncFn` has returned. | ||
| * Hook for creating an array with several setters for ease of use. | ||
| * | ||
| * @param asyncFn - Async function that will be run . | ||
| * @param args - Array of arguments for that `asyncFn` takes. | ||
| * @param dependencies - `asyncFn` will run each time the values of this array change. | ||
| * | ||
| * | ||
| * @returns Object holding the current status (`loading`) and either the resulting data or an error. | ||
| * @public | ||
| * @param initialState - Initial state value | ||
| */ | ||
| export declare const useAsyncFunction: <T>(asyncFn: AsyncFunction<T>, args?: unknown[], dependencies?: unknown[]) => AsyncFunctionState<T>; | ||
| export declare const useArray: <T>(initialState: T[] | (() => T[])) => [T[], ArraySetter<T>]; | ||
@@ -92,5 +98,5 @@ /** | ||
| * | ||
| * @public | ||
| * @param value - Either the state value or its resolver | ||
| * @returns A getter for the state value | ||
| * @public | ||
| */ | ||
@@ -102,7 +108,7 @@ export declare const useConstant: <T>(value: T | (() => T)) => () => T; | ||
| * | ||
| * @param initialValue - Either the initial value or a function that resolves to it for lazy loading. | ||
| * @public | ||
| * @param initialState - Either the initial value or a function that resolves to it for lazy loading. | ||
| * @returns A tuple with the state value, and an object with its setters. | ||
| * @public | ||
| */ | ||
| export declare const useCounter: (initialValue: number | (() => number)) => [number, CounterSetter]; | ||
| export declare const useCounter: (initialState: number | (() => number)) => [number, CounterSetter]; | ||
@@ -113,4 +119,4 @@ /** | ||
| * | ||
| * @public | ||
| * @param effect - Imperative function that can return a cleanup function. | ||
| * @public | ||
| */ | ||
@@ -127,7 +133,7 @@ export declare const useEffectOnce: (effect: EffectCallback) => void; | ||
| * | ||
| * @public | ||
| * @param callback - The callback to freeze. | ||
| * @returns The freezed callback. | ||
| * @public | ||
| */ | ||
| export declare const useFreezedCallback: <T>(callback: GenericFunction<T>) => GenericFunction<T>; | ||
| export declare const useFreezedCallback: <T extends (...args: any[]) => any>(callback: T) => T; | ||
@@ -141,3 +147,3 @@ /** | ||
| */ | ||
| export declare const useStateObject: (initialState: object) => [object, StateObjectSetter]; | ||
| export declare const useObject: <T extends object>(initialState: T) => [T, ObjectSetter<T>]; | ||
@@ -149,7 +155,5 @@ /** | ||
| * | ||
| * @public | ||
| * @param initialValue - Either the initial value or a function that resolves to it for lazy loading. | ||
| * | ||
| * @returns A tuple with the current state, the state toggler, and a object with `true` and `false` setters. | ||
| * | ||
| * @public | ||
| */ | ||
@@ -156,0 +160,0 @@ export declare const useToggle: (initialValue: boolean | (() => boolean)) => [boolean, TogglerSetter]; |
@@ -1,2 +0,2 @@ | ||
| !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@react-hookful/core"]={},e.react)}(this,(function(e,t){"use strict";const s=e=>{const s=t.useRef();return s.current||(s.current=e),s.current},r=e=>{const[s,r]=t.useState(e),u=t.useCallback((e=>r((t=>({...t,...e})))),[r]),n=t.useCallback((()=>r(e)),[r,e]),c=t.useCallback((()=>r({})),[r]);return[s,{set:r,merge:u,reset:n,clear:c}]},u=e=>(e=>"function"==typeof e)(e)?e():e;e.useAsyncFunction=(e,s=[],u=[])=>{const[n,c]=r({data:null,loading:!0,error:null}),a=t.useCallback((async()=>{try{const t=await e(...s);c.merge({data:t,loading:!1})}catch(e){c.merge({error:e,loading:!1})}}),u);return t.useEffect((()=>{a()}),u),n},e.useConstant=e=>{const r=t.useRef();return s((()=>(r.current||(r.current={state:u(e)}),r.current.state)))},e.useCounter=e=>{const[s,r]=t.useState(e),n=t.useCallback(((e=1)=>r((t=>t+e))),[r]),c=t.useCallback(((e=1)=>r((t=>t-e))),[r]),a=t.useCallback((()=>r(u(e))),[r,e]);return[s,{set:r,inc:n,dec:c,reset:a}]},e.useEffectOnce=e=>{t.useEffect(e,[])},e.useFreezedCallback=s,e.useStateObject=r,e.useToggle=e=>{const[s,r]=t.useState(e),u=t.useCallback((()=>r(!0)),[r]),n=t.useCallback((()=>r(!1)),[r]);return[s,{toggle:s?n:u,setTrue:u,setFalse:n,set:r}]},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
| !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@react-hookful/core"]={},e.react)}(this,(function(e,t){"use strict";const s=e=>{const s=t.useRef();return s.current||(s.current=e),s.current},u=e=>(e=>"function"==typeof e)(e)?e():e;e.useArray=e=>{const[s,a]=t.useState(e),r=t.useCallback((e=>a((t=>[...t,e]))),[a]),c=t.useCallback((e=>a((t=>[e,...t]))),[a]),l=t.useCallback((e=>a((t=>[...t,...e]))),[a]),n=t.useCallback((()=>{let e=s[0];return a((([t,...s])=>(e=t,s))),e}),[a,s]),o=t.useCallback((()=>{let e=s.slice(-1)[0];return a((t=>(e=t.slice(-1)[0],t.slice(0,-1)))),e}),[a,s]),f=t.useCallback(((e,t)=>{a((s=>s.map(e,t)))}),[a]),b=t.useCallback(((e,t)=>{a((s=>s.filter(e,t)))}),[a]),i=t.useCallback((()=>a([])),[a]),C=t.useCallback((()=>a(u(e))),[a,e]);return[s,{set:a,append:r,prepend:c,pop:o,transform:f,filter:b,shift:n,concat:l,reset:C,clear:i}]},e.useConstant=e=>{const a=t.useRef();return s((()=>(a.current||(a.current={state:u(e)}),a.current.state)))},e.useCounter=e=>{const[s,a]=t.useState(e),r=t.useCallback(((e=1)=>a((t=>t+e))),[a]),c=t.useCallback(((e=1)=>a((t=>t-e))),[a]),l=t.useCallback((()=>a(u(e))),[a,e]);return[s,{set:a,inc:r,dec:c,reset:l}]},e.useEffectOnce=e=>{t.useEffect(e,[])},e.useFreezedCallback=s,e.useObject=e=>{const[s,a]=t.useState(e),r=t.useCallback((e=>a((t=>({...t,...u(e)})))),[a]),c=t.useCallback((()=>a(e)),[a,e]);return[s,{set:a,merge:r,reset:c}]},e.useToggle=e=>{const[s,u]=t.useState(e),a=t.useCallback((()=>u(!0)),[u]),r=t.useCallback((()=>u(!1)),[u]);return[s,{toggle:s?r:a,setTrue:a,setFalse:r,set:u}]},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
| //# sourceMappingURL=index.umd.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.umd.js","sources":["../src/useFreezedCallback/useFreezedCallback.ts","../src/useStateObject/useStateObject.ts","../src/utils.ts","../src/useAsyncFunction/useAsyncFunction.ts","../src/useConstant/useConstant.ts","../src/useCounter/useCounter.ts","../src/useEffectOnce/useEffectOnce.ts","../src/useToggle/useToggle.ts"],"sourcesContent":["import { useRef } from 'react';\nimport { GenericFunction } from '../types';\n\n/**\n * Hook that freezed a given callback, so it is only created once in the components life.\n * It ensures the return function is always the same.\n *\n * Useful for optimizations where otherwise constant functions are recalculated every re-render\n *\n * Should the callback ever be recalculated see `React.useCallback` and `React.useMemo`.\n *\n * @param callback - The callback to freeze.\n * @returns The freezed callback.\n * @public\n */\nexport const useFreezedCallback = <T>(callback: GenericFunction<T>): GenericFunction<T> => {\n const reference = useRef<GenericFunction<T>>();\n\n if (!reference.current) {\n reference.current = callback;\n }\n\n return reference.current;\n};\n","import { useState, useCallback } from 'react';\n\n/** Setters of the state maintained by `useStateObject`\n * @public\n */\nexport interface StateObjectSetter {\n /** Merges the current state with the `arg` object. */\n merge: (arg: object) => void;\n /** State setter, the same you would get with `React.useState`. */\n set: (arg: object | ((prevState: object) => object)) => void;\n /** Resets the state back to the initial one. */\n reset: () => void;\n /** Sets the state to an empty object (`{}`). */\n clear: () => void;\n}\n\n/**\n * Hook for creating an object with several setters for ease of use. Like state merging and resetting.\n *\n * @param initialState - Initial state value.\n * @returns A tuple with the current state, and the setters.\n * @public\n */\nexport const useStateObject = (initialState: object): [object, StateObjectSetter] => {\n const [state, set] = useState(initialState);\n\n const merge = useCallback(\n (newState: object) => set(prevState => ({ ...prevState, ...newState })),\n [set],\n );\n\n const reset = useCallback(() => set(initialState), [set, initialState]);\n const clear = useCallback(() => set({}), [set]);\n\n return [state, { set, merge, reset, clear }];\n};\n","/** @internal */\nexport const isFunction = (value: unknown): value is Function => typeof value === 'function';\n\n/** @internal */\nexport const resolveValue = <T>(value: T | (() => T)): T => (isFunction(value) ? value() : value);\n","import { useEffect, useCallback } from 'react';\nimport { useStateObject } from '../useStateObject';\n\nimport { AsyncFunction } from '../types';\n\n/**\n * @public\n */\nexport interface AsyncFunctionState<T> {\n data: T;\n loading: boolean;\n error: unknown;\n}\n\n/**\n * Useful hook for running side effects and monitor their current state.\n * `loading` flag is initialized to `true` and changes to `false` once `asyncFn` has returned.\n *\n * @param asyncFn - Async function that will be run .\n * @param args - Array of arguments for that `asyncFn` takes.\n * @param dependencies - `asyncFn` will run each time the values of this array change.\n *\n *\n * @returns Object holding the current status (`loading`) and either the resulting data or an error.\n * @public\n */\nexport const useAsyncFunction = <T>(\n asyncFn: AsyncFunction<T>,\n args: unknown[] = [],\n dependencies: unknown[] = [],\n): AsyncFunctionState<T> => {\n const [state, setState] = useStateObject({\n data: null,\n loading: true,\n error: null,\n });\n\n const runAsyncFn = useCallback(async () => {\n try {\n const data = await asyncFn(...args);\n setState.merge({ data, loading: false });\n } catch (error) {\n setState.merge({ error, loading: false });\n }\n }, dependencies); // eslint-disable-line\n\n useEffect(() => {\n runAsyncFn();\n }, dependencies); // eslint-disable-line\n\n return state as AsyncFunctionState<T>;\n};\n","import { useRef } from 'react';\nimport { useFreezedCallback } from '../useFreezedCallback';\nimport { resolveValue } from '../utils';\n\n/**\n * Hook to keep a constant state value.\n * It takes an value or a resolver and maintains a reference to it though re-renders.\n *\n * Returns a getter for state value so it can be lazily set.\n *\n * `React.useState` can be used as an alternative although it should be less performing since it relies on reducers.\n *\n * Should the value change based on dependencies consider `React.useMemo`.\n * Should the value be a reference to a function consider `useFreezedCallback`.\n *\n * @param value - Either the state value or its resolver\n * @returns A getter for the state value\n * @public\n */\nexport const useConstant = <T>(value: T | (() => T)): (() => T) => {\n const reference = useRef<{ state: T }>();\n\n const get = useFreezedCallback(() => {\n if (!reference.current) {\n reference.current = {\n state: resolveValue(value),\n };\n }\n\n return reference.current.state;\n });\n\n return get;\n};\n","import { useState, useCallback } from 'react';\nimport { resolveValue } from '../utils';\n\n/**\n * Signature of the setters provided by `useCounter`\n * @public\n */\nexport interface CounterSetter {\n /** Sets the state to a given value */\n set: (value: number | ((prev: number) => number)) => void;\n /** Increments the state by a given value. Defaults to `1` */\n inc: (value?: number) => void;\n /** Decrements the state by a given value. Defaults to `1` */\n dec: (value?: number) => void;\n /** Resets the state back to its initial value */\n reset: () => void;\n}\n\n/**\n * Simple hook to keep a numeric state with some useful setters.\n *\n * @param initialValue - Either the initial value or a function that resolves to it for lazy loading.\n * @returns A tuple with the state value, and an object with its setters.\n * @public\n */\nexport const useCounter = (initialValue: number | (() => number)): [number, CounterSetter] => {\n const [value, set] = useState(initialValue);\n\n const inc = useCallback(\n (increment = 1): void => set((prevValue: number) => prevValue + increment),\n [set],\n );\n\n const dec = useCallback(\n (decrement = 1): void => set((prevValue: number) => prevValue - decrement),\n [set],\n );\n\n const reset = useCallback((): void => set(resolveValue(initialValue)), [set, initialValue]);\n\n return [value, { set, inc, dec, reset }];\n};\n","import { useEffect, EffectCallback } from 'react';\n\n/**\n * This hook its a simple wrapper of `React.useEffect` with and empty dependencies array.\n * It ensures the return function is always the same.\n *\n * @param effect - Imperative function that can return a cleanup function.\n * @public\n */\nexport const useEffectOnce = (effect: EffectCallback): void => {\n useEffect(effect, []); // eslint-disable-line\n};\n","import { useState, useCallback } from 'react';\n\n/** Setters of the state maintained by `useToggle`\n * @public\n */\nexport interface TogglerSetter {\n /** Toggles the state value between `true` and `false` */\n toggle: () => void;\n /** Sets the state value to `true` */\n setTrue: () => void;\n /** Sets the state value to `false` */\n setFalse: () => void;\n /** Sets the state value to a given boolean */\n set: (arg: boolean | (() => boolean)) => void;\n}\n\n/**\n * Hook that stores a boolean value, and provides logic for toggling and setting the value.\n *\n * The return value is a tuple with the value, toggler, and a object with the `true` and `false` setters.\n *\n * @param initialValue - Either the initial value or a function that resolves to it for lazy loading.\n *\n * @returns A tuple with the current state, the state toggler, and a object with `true` and `false` setters.\n *\n * @public\n */\nexport const useToggle = (initialValue: boolean | (() => boolean)): [boolean, TogglerSetter] => {\n const [value, set] = useState(initialValue);\n\n const setTrue = useCallback(() => set(true), [set]);\n const setFalse = useCallback(() => set(false), [set]);\n const toggle = value ? setFalse : setTrue;\n\n return [value, { toggle, setTrue, setFalse, set }];\n};\n"],"names":["useFreezedCallback","callback","reference","useRef","current","useStateObject","initialState","state","set","useState","merge","useCallback","newState","prevState","reset","clear","resolveValue","value","isFunction","asyncFn","args","dependencies","setState","data","loading","error","runAsyncFn","async","useEffect","initialValue","inc","increment","prevValue","dec","decrement","effect","setTrue","setFalse","toggle"],"mappings":"uSAeaA,EAAyBC,IACpC,MAAMC,EAAYC,WAMlB,OAJKD,EAAUE,UACbF,EAAUE,QAAUH,GAGfC,EAAUE,SCCNC,EAAkBC,IAC7B,MAAOC,EAAOC,GAAOC,WAASH,GAExBI,EAAQC,eACXC,GAAqBJ,GAAIK,QAAmBA,KAAcD,OAC3D,CAACJ,IAGGM,EAAQH,eAAY,IAAMH,EAAIF,IAAe,CAACE,EAAKF,IACnDS,EAAQJ,eAAY,IAAMH,EAAI,KAAK,CAACA,IAE1C,MAAO,CAACD,EAAO,CAAEC,IAAAA,EAAKE,MAAAA,EAAOI,MAAAA,EAAOC,MAAAA,KC9BzBC,EAAmBC,GAHN,CAACA,GAAuD,mBAAVA,EAGXC,CAAWD,GAASA,IAAUA,qBCsB3D,CAC9BE,EACAC,EAAkB,GAClBC,EAA0B,MAE1B,MAAOd,EAAOe,GAAYjB,EAAe,CACvCkB,KAAM,KACNC,SAAS,EACTC,MAAO,OAGHC,EAAaf,eAAYgB,UAC7B,IACE,MAAMJ,QAAaJ,KAAWC,GAC9BE,EAASZ,MAAM,CAAEa,KAAAA,EAAMC,SAAS,IAChC,MAAOC,GACPH,EAASZ,MAAM,CAAEe,MAAAA,EAAOD,SAAS,OAElCH,GAMH,OAJAO,aAAU,KACRF,MACCL,GAEId,iBC/BsBU,IAC7B,MAAMf,EAAYC,WAYlB,OAVYH,GAAmB,KACxBE,EAAUE,UACbF,EAAUE,QAAU,CAClBG,MAAOS,EAAaC,KAIjBf,EAAUE,QAAQG,uBCJFsB,IACzB,MAAOZ,EAAOT,GAAOC,WAASoB,GAExBC,EAAMnB,eACV,CAACoB,EAAY,IAAYvB,GAAKwB,GAAsBA,EAAYD,KAChE,CAACvB,IAGGyB,EAAMtB,eACV,CAACuB,EAAY,IAAY1B,GAAKwB,GAAsBA,EAAYE,KAChE,CAAC1B,IAGGM,EAAQH,eAAY,IAAYH,EAAIQ,EAAaa,KAAgB,CAACrB,EAAKqB,IAE7E,MAAO,CAACZ,EAAO,CAAET,IAAAA,EAAKsB,IAAAA,EAAKG,IAAAA,EAAKnB,MAAAA,qBC/BJqB,IAC5BP,YAAUO,EAAQ,2DCiBMN,IACxB,MAAOZ,EAAOT,GAAOC,WAASoB,GAExBO,EAAUzB,eAAY,IAAMH,GAAI,IAAO,CAACA,IACxC6B,EAAW1B,eAAY,IAAMH,GAAI,IAAQ,CAACA,IAGhD,MAAO,CAACS,EAAO,CAAEqB,OAFFrB,EAAQoB,EAAWD,EAETA,QAAAA,EAASC,SAAAA,EAAU7B,IAAAA"} | ||
| {"version":3,"file":"index.umd.js","sources":["../src/useFreezedCallback/useFreezedCallback.ts","../src/utils.ts","../src/useArray/useArray.ts","../src/useConstant/useConstant.ts","../src/useCounter/useCounter.ts","../src/useEffectOnce/useEffectOnce.ts","../src/useObject/useObject.ts","../src/useToggle/useToggle.ts"],"sourcesContent":["import { useRef } from 'react';\n\n/**\n * Hook that freezed a given callback, so it is only created once in the components life.\n * It ensures the return function is always the same.\n *\n * Useful for optimizations where otherwise constant functions are recalculated every re-render\n *\n * Should the callback ever be recalculated see `React.useCallback` and `React.useMemo`.\n *\n * @public\n * @param callback - The callback to freeze.\n * @returns The freezed callback.\n */\nexport const useFreezedCallback = <T extends (...args: any[]) => any>(\n callback: T,\n): T => {\n const reference = useRef<T>();\n\n if (!reference.current) {\n reference.current = callback;\n }\n\n return reference.current;\n};\n","/** @internal */\nexport const isFunction = (value: unknown): value is Function =>\n typeof value === 'function';\n\n/** @internal */\nexport const resolveValue = <T>(value: T | ((...args: any[]) => T)): T =>\n isFunction(value) ? value() : value;\n","import { useCallback, useState } from 'react';\nimport { resolveValue } from '../utils';\n\n/**\n * @public\n * Setters for the state maintained by `useArray`\n */\nexport interface ArraySetter<T> {\n /** Sets the state, the same you would get with `React.useState`. */\n set: React.Dispatch<React.SetStateAction<T[]>>;\n /** Appends an element to the state */\n append: (element: T) => void;\n /** Prepends an element to the state */\n prepend: (element: T) => void;\n /** Removes and returns the last element from the state */\n pop: () => T;\n /** Removes and returns the first element from the state */\n shift: () => T;\n /** Concatenates a given array to the state */\n concat: (elements: T[]) => void;\n /** Allows you to transform each element of the state, with the same API as `Array.prototype.map` */\n transform: (\n callbackfn: (value: T, index: number, array: T[]) => T,\n thisArg?: any,\n ) => void;\n /** Like `Array.prototype.filter` */\n filter: (\n predicate: (value: T, index: number, array: T[]) => boolean,\n thisArg?: any,\n ) => void;\n /** Resets the state back to the initial value */\n reset: () => void;\n /** Sets the state to `[]` */\n clear: () => void;\n}\n\n/**\n * Hook for creating an array with several setters for ease of use.\n *\n * @public\n * @param initialState - Initial state value\n */\nexport const useArray = <T>(\n initialState: T[] | (() => T[]),\n): [T[], ArraySetter<T>] => {\n const [state, set] = useState(initialState);\n\n const append: ArraySetter<T>['append'] = useCallback(\n (element: T) => set(current => [...current, element]),\n [set],\n );\n\n const prepend: ArraySetter<T>['prepend'] = useCallback(\n (element: T) => set(current => [element, ...current]),\n [set],\n );\n\n const concat: ArraySetter<T>['concat'] = useCallback(\n (elements: T[]) => set(current => [...current, ...elements]),\n [set],\n );\n\n const shift: ArraySetter<T>['shift'] = useCallback(() => {\n let result: T = state[0];\n\n set(([head, ...tail]) => {\n result = head;\n return tail;\n });\n\n return result;\n }, [set, state]);\n\n const pop: ArraySetter<T>['pop'] = useCallback(() => {\n let result: T = state.slice(-1)[0];\n\n set(current => {\n result = current.slice(-1)[0];\n return current.slice(0, -1);\n });\n\n return result;\n }, [set, state]);\n\n const transform: ArraySetter<T>['transform'] = useCallback(\n (callback, thisArg) => {\n set(current => current.map(callback, thisArg));\n },\n [set],\n );\n\n const filter: ArraySetter<T>['filter'] = useCallback(\n (callback, thisArg) => {\n set(current => current.filter(callback, thisArg));\n },\n [set],\n );\n\n const clear: ArraySetter<T>['clear'] = useCallback((): void => set([]), [\n set,\n ]);\n\n const reset: ArraySetter<T>['reset'] = useCallback(\n (): void => set(resolveValue(initialState)),\n [set, initialState],\n );\n\n return [\n state,\n {\n set,\n append,\n prepend,\n pop,\n transform,\n filter,\n shift,\n concat,\n reset,\n clear,\n },\n ];\n};\n","import { useRef } from 'react';\nimport { useFreezedCallback } from '../useFreezedCallback';\nimport { resolveValue } from '../utils';\n\n/**\n * Hook to keep a constant state value.\n * It takes an value or a resolver and maintains a reference to it though re-renders.\n *\n * Returns a getter for state value so it can be lazily set.\n *\n * `React.useState` can be used as an alternative although it should be less performing since it relies on reducers.\n *\n * Should the value change based on dependencies consider `React.useMemo`.\n * Should the value be a reference to a function consider `useFreezedCallback`.\n *\n * @public\n * @param value - Either the state value or its resolver\n * @returns A getter for the state value\n */\nexport const useConstant = <T>(value: T | (() => T)): (() => T) => {\n const reference = useRef<{ state: T }>();\n\n const get = useFreezedCallback(() => {\n if (!reference.current) {\n reference.current = {\n state: resolveValue(value),\n };\n }\n\n return reference.current.state;\n });\n\n return get;\n};\n","import { useState, useCallback } from 'react';\nimport { resolveValue } from '../utils';\n\n/**\n * Signature of the setters provided by `useCounter`\n * @public\n */\nexport interface CounterSetter {\n /** Sets the state to a given value */\n set: (value: number | ((prev: number) => number)) => void;\n /** Increments the state by a given value. Defaults to `1` */\n inc: (value?: number) => void;\n /** Decrements the state by a given value. Defaults to `1` */\n dec: (value?: number) => void;\n /** Resets the state back to its initial value */\n reset: () => void;\n}\n\n/**\n * Simple hook to keep a numeric state with some useful setters.\n *\n * @public\n * @param initialState - Either the initial value or a function that resolves to it for lazy loading.\n * @returns A tuple with the state value, and an object with its setters.\n */\nexport const useCounter = (\n initialState: number | (() => number),\n): [number, CounterSetter] => {\n const [value, set] = useState(initialState);\n\n const inc = useCallback(\n (increment = 1): void => set((currState: number) => currState + increment),\n [set],\n );\n\n const dec = useCallback(\n (decrement = 1): void => set((currState: number) => currState - decrement),\n [set],\n );\n\n const reset = useCallback((): void => set(resolveValue(initialState)), [\n set,\n initialState,\n ]);\n\n return [value, { set, inc, dec, reset }];\n};\n","import { useEffect, EffectCallback } from 'react';\n\n/**\n * This hook its a simple wrapper of `React.useEffect` with and empty dependencies array.\n * It ensures the return function is always the same.\n *\n * @public\n * @param effect - Imperative function that can return a cleanup function.\n */\nexport const useEffectOnce = (effect: EffectCallback): void => {\n useEffect(effect, []); // eslint-disable-line\n};\n","import { useState, useCallback } from 'react';\nimport { resolveValue } from '../utils';\n\n/** Setters of the state maintained by `useObject`\n * @public\n */\nexport interface ObjectSetter<T extends object> {\n /** Merges the current state with the `arg` object. */\n merge: (arg: Partial<T> | ((currState: T) => Partial<T>)) => void;\n /** State setter, the same you would get with `React.useState`. */\n set: React.Dispatch<React.SetStateAction<T>>;\n /** Resets the state back to the initial one. */\n reset: () => void;\n}\n\n/**\n * Hook for creating an object with several setters for ease of use. Like state merging and resetting.\n *\n * @param initialState - Initial state value.\n * @returns A tuple with the current state, and the setters.\n * @public\n */\nexport const useObject = <T extends object>(\n initialState: T,\n): [T, ObjectSetter<T>] => {\n const [state, set] = useState(initialState);\n\n const merge = useCallback(\n (newState: Partial<T> | ((currState: T) => Partial<T>)) =>\n set(currState => ({ ...currState, ...resolveValue(newState) })),\n [set],\n );\n\n const reset = useCallback(() => set(initialState), [set, initialState]);\n\n return [state, { set, merge, reset }];\n};\n","import { useState, useCallback } from 'react';\n\n/** Setters of the state maintained by `useToggle`\n * @public\n */\nexport interface TogglerSetter {\n /** Toggles the state value between `true` and `false` */\n toggle: () => void;\n /** Sets the state value to `true` */\n setTrue: () => void;\n /** Sets the state value to `false` */\n setFalse: () => void;\n /** Sets the state value to a given boolean */\n set: (arg: boolean | (() => boolean)) => void;\n}\n\n/**\n * Hook that stores a boolean value, and provides logic for toggling and setting the value.\n *\n * The return value is a tuple with the value, toggler, and a object with the `true` and `false` setters.\n *\n * @public\n * @param initialValue - Either the initial value or a function that resolves to it for lazy loading.\n * @returns A tuple with the current state, the state toggler, and a object with `true` and `false` setters.\n */\nexport const useToggle = (\n initialValue: boolean | (() => boolean),\n): [boolean, TogglerSetter] => {\n const [value, set] = useState(initialValue);\n\n const setTrue = useCallback(() => set(true), [set]);\n const setFalse = useCallback(() => set(false), [set]);\n const toggle = value ? setFalse : setTrue;\n\n return [value, { toggle, setTrue, setFalse, set }];\n};\n"],"names":["useFreezedCallback","callback","reference","useRef","current","resolveValue","value","isFunction","initialState","state","set","useState","append","useCallback","element","prepend","concat","elements","shift","result","head","tail","pop","slice","transform","thisArg","map","filter","clear","reset","inc","increment","currState","dec","decrement","effect","useEffect","merge","newState","initialValue","setTrue","setFalse","toggle"],"mappings":"uSAcaA,EACXC,IAEA,MAAMC,EAAYC,WAMlB,OAJKD,EAAUE,UACbF,EAAUE,QAAUH,GAGfC,EAAUE,SClBNC,EAAmBC,GAJN,CAACA,GACR,mBAAVA,EAIPC,CAAWD,GAASA,IAAUA,aCqC9BE,IAEA,MAAOC,EAAOC,GAAOC,WAASH,GAExBI,EAAmCC,eACtCC,GAAeJ,GAAIN,GAAW,IAAIA,EAASU,MAC5C,CAACJ,IAGGK,EAAqCF,eACxCC,GAAeJ,GAAIN,GAAW,CAACU,KAAYV,MAC5C,CAACM,IAGGM,EAAmCH,eACtCI,GAAkBP,GAAIN,GAAW,IAAIA,KAAYa,MAClD,CAACP,IAGGQ,EAAiCL,eAAY,KACjD,IAAIM,EAAYV,EAAM,GAOtB,OALAC,GAAI,EAAEU,KAASC,MACbF,EAASC,EACFC,KAGFF,IACN,CAACT,EAAKD,IAEHa,EAA6BT,eAAY,KAC7C,IAAIM,EAAYV,EAAMc,OAAO,GAAG,GAOhC,OALAb,GAAIN,IACFe,EAASf,EAAQmB,OAAO,GAAG,GACpBnB,EAAQmB,MAAM,GAAI,MAGpBJ,IACN,CAACT,EAAKD,IAEHe,EAAyCX,eAC7C,CAACZ,EAAUwB,KACTf,GAAIN,GAAWA,EAAQsB,IAAIzB,EAAUwB,OAEvC,CAACf,IAGGiB,EAAmCd,eACvC,CAACZ,EAAUwB,KACTf,GAAIN,GAAWA,EAAQuB,OAAO1B,EAAUwB,OAE1C,CAACf,IAGGkB,EAAiCf,eAAY,IAAYH,EAAI,KAAK,CACtEA,IAGImB,EAAiChB,eACrC,IAAYH,EAAIL,EAAaG,KAC7B,CAACE,EAAKF,IAGR,MAAO,CACLC,EACA,CACEC,IAAAA,EACAE,OAAAA,EACAG,QAAAA,EACAO,IAAAA,EACAE,UAAAA,EACAG,OAAAA,EACAT,MAAAA,EACAF,OAAAA,EACAa,MAAAA,EACAD,MAAAA,mBCpGyBtB,IAC7B,MAAMJ,EAAYC,WAYlB,OAVYH,GAAmB,KACxBE,EAAUE,UACbF,EAAUE,QAAU,CAClBK,MAAOJ,EAAaC,KAIjBJ,EAAUE,QAAQK,uBCH3BD,IAEA,MAAOF,EAAOI,GAAOC,WAASH,GAExBsB,EAAMjB,eACV,CAACkB,EAAY,IAAYrB,GAAKsB,GAAsBA,EAAYD,KAChE,CAACrB,IAGGuB,EAAMpB,eACV,CAACqB,EAAY,IAAYxB,GAAKsB,GAAsBA,EAAYE,KAChE,CAACxB,IAGGmB,EAAQhB,eAAY,IAAYH,EAAIL,EAAaG,KAAgB,CACrEE,EACAF,IAGF,MAAO,CAACF,EAAO,CAAEI,IAAAA,EAAKoB,IAAAA,EAAKG,IAAAA,EAAKJ,MAAAA,qBCpCJM,IAC5BC,YAAUD,EAAQ,wCCalB3B,IAEA,MAAOC,EAAOC,GAAOC,WAASH,GAExB6B,EAAQxB,eACXyB,GACC5B,GAAIsB,QAAmBA,KAAc3B,EAAaiC,QACpD,CAAC5B,IAGGmB,EAAQhB,eAAY,IAAMH,EAAIF,IAAe,CAACE,EAAKF,IAEzD,MAAO,CAACC,EAAO,CAAEC,IAAAA,EAAK2B,MAAAA,EAAOR,MAAAA,iBCT7BU,IAEA,MAAOjC,EAAOI,GAAOC,WAAS4B,GAExBC,EAAU3B,eAAY,IAAMH,GAAI,IAAO,CAACA,IACxC+B,EAAW5B,eAAY,IAAMH,GAAI,IAAQ,CAACA,IAGhD,MAAO,CAACJ,EAAO,CAAEoC,OAFFpC,EAAQmC,EAAWD,EAETA,QAAAA,EAASC,SAAAA,EAAU/B,IAAAA"} |
+5
-5
| { | ||
| "name": "@react-hookful/core", | ||
| "version": "0.1.0-alpha.9", | ||
| "version": "0.2.0", | ||
| "description": "Useful react hooks that help you clean up you functional components.", | ||
@@ -44,3 +44,3 @@ "keywords": [ | ||
| "@types/react-dom": "^16.9.6", | ||
| "jest": "^25.3.0", | ||
| "jest": "^26.6.1", | ||
| "react-dom": "^16.13.1", | ||
@@ -51,4 +51,4 @@ "react-test-renderer": "^16.13.1", | ||
| "rollup-plugin-typescript2": "^0.28.0", | ||
| "ts-jest": "^25.3.1", | ||
| "typescript": "^3.8.3" | ||
| "ts-jest": "^26.4.3", | ||
| "typescript": "^4.0.5" | ||
| }, | ||
@@ -64,3 +64,3 @@ "peerDependencies": { | ||
| ], | ||
| "gitHead": "0d88ec9ba686185b72e3d6da43d26f02faf12243" | ||
| "gitHead": "13d46156ac2ca2adb060b2daf87c3d56b8c19908" | ||
| } |
+51
-52
@@ -5,6 +5,14 @@ # <h1 align="center">@react-hookful/core</h1> | ||
| <a href="https://www.npmjs.com/package/@react-hookful/core"> | ||
| <img alt="npm (scoped)" src="https://img.shields.io/npm/v/@react-hookful/core?style=plastic"> | ||
| <img alt="npm (scoped)" src="https://img.shields.io/npm/v/@react-hookful/core?style=flat-square&logo=npm"> | ||
| </a> | ||
| <img alt="npm bundle size (scoped)" src="https://img.shields.io/bundlephobia/minzip/@react-hookful/core?style=plastic"> | ||
| <img alt="npm bundle size (scoped)" src="https://img.shields.io/bundlephobia/minzip/@react-hookful/core?style=flat-square"> | ||
| <img alt="NPM" src="https://img.shields.io/npm/l/@react-hookful/core?style=flat-square"> | ||
| <img alt="npm" src="https://img.shields.io/npm/dm/@react-hookful/core?style=flat-square"> | ||
| <img alt="CircleCI" src="https://img.shields.io/circleci/build/github/Frantss/react-hookful/master?label=master&logo=circleci&style=flat-square&token=c97c78f1040c038c4857e8bbc6ab5a4acc310455"> | ||
| <img alt="CircleCI" src="https://img.shields.io/circleci/build/github/Frantss/react-hookful/develop?label=develop&logo=circleci&style=flat-square&token=c97c78f1040c038c4857e8bbc6ab5a4acc310455"> | ||
| </p> | ||
@@ -27,3 +35,3 @@ | ||
| # Yarn | ||
| yarn install @react-hookful/core | ||
| yarn add @react-hookful/core | ||
| ``` | ||
@@ -33,7 +41,7 @@ | ||
| - [useAsyncFunction](#useasyncfunction) - Runs an async function and keeps track of its result, status, and error | ||
| - [useEffectOnce](#useeffectonce) - A semantic replacement for `useEffect` with | ||
| an empty dependencies array | ||
| - [useFreezedCallback](#usefreezedcallback) - Returns a constant version of the function passed as argument | ||
| - [useStateObject](#usestateobject) - Like `useState` but for objects, with state built-in merging | ||
| - [useObject](#useObject) - Like `useState` but for objects, with state built-in merging | ||
| - [useArray](#useArray) - Like `useState` but for arrays, with built-in useful setters | ||
| - [useToggle](#usetoggle) - Returns a boolean value with toggler and setters | ||
@@ -43,32 +51,2 @@ - [useCounter](#usecounter) - Returns a numeric value with useful setters. | ||
| ### useAsyncFunction | ||
| ```tsx | ||
| useAsyncFunction<T>(asyncFn: AsyncFunction<T>, args: unknown[] = [], dependencies: unknown[] = []): AsyncFunctionState<T> | ||
| ``` | ||
| Hook for running side effects and monitor their current state. | ||
| `loading` flag is initialized to `true` and changes to `false` once `asyncFn` has been resolved. | ||
| #### `AsyncFunctionState<T>` interface | ||
| - data: T - The result of the async function passed as an argument. | ||
| - loading: boolean - Indicates whether the async function is still running. | ||
| - error: unknown - In case an error occurs while executing the function it is stored in this value. | ||
| #### Example | ||
| ```jsx | ||
| import { useAsyncFunction } from '@react-hookful/core'; | ||
| const Component = () => { | ||
| const { data, loading, error } = useAsyncFunction(() => { | ||
| /* some asynchronous function */ | ||
| }); | ||
| const result = useAsyncFunction(/* some asynchronous function reference */); | ||
| }; | ||
| ``` | ||
| ### useEffectOnce | ||
@@ -98,3 +76,3 @@ | ||
| ```tsx | ||
| useFreezedCallback<T>(callback: GenericFunction<T>): GenericFunction<T>] | ||
| useFreezedCallback<T extends GenericFunction<T>>(callback: T): T | ||
| ``` | ||
@@ -121,6 +99,6 @@ | ||
| ### useStateObject | ||
| ### useObject | ||
| ```tsx | ||
| useStateObject(initialState: object): [object, StateObjectSetter] | ||
| useObject<T extends object>(initialState: T): [T, StateObjectSetter<T>] | ||
| ``` | ||
@@ -132,6 +110,5 @@ | ||
| - `merge: (arg: object) => void` - Merges the current state with the `arg` object. | ||
| - `set: (arg: object | ((prevState: object) => object)) => void` - State setter, the same you would get with `React.useState`. | ||
| - `merge: <T>(arg: Partial<T>) => void` - Merges the current state with the `arg` object. | ||
| - `set: (arg: T | ((currState: T) => T)) => void` - State setter, the same you would get with `React.useState`. | ||
| - `reset: () => void` - Resets the state back to the initial one. | ||
| - `clear: () => void` - Sets the state to an empty object (`{}`). | ||
@@ -141,24 +118,43 @@ #### Example | ||
| ```jsx | ||
| import { useStateObject } from '@react-hookful/core'; | ||
| import { useObject } from '@react-hookful/core'; | ||
| const Component = () => { | ||
| const [state, setState] = useStateObject({ username: 'arumba' }); | ||
| const [state, setState] = useObject({ username: 'arumba', password: '123' }); | ||
| setState.merge({ username: 'fernir', password: '123' }); | ||
| setState.merge({ username: 'fernir' }); | ||
| console.log(state); // {username: 'fernir', password: '123'} | ||
| setState.set({ password: 'password' }); | ||
| console.log(state); // {username: 'fernir', password: 'password'} | ||
| setState.set({ username: 'something', password: 'password' }); | ||
| console.log(state); // {username: 'something', password: 'password'} | ||
| setState.set(prevState => ({ ...prevState, username: 'sofi' })); | ||
| setState.set(currState => ({ ...currState, username: 'sofi' })); // Same as `.merge` | ||
| console.log(state); // {username: 'sofi', password: 'password'} | ||
| setState.reset(); | ||
| console.log(state); // { username: 'arumba'} | ||
| console.log(state); // { username: 'arumba', password: '123' } | ||
| setState.clear(); | ||
| console.log(state); // {} | ||
| }; | ||
| ``` | ||
| ### useArray | ||
| ```tsx | ||
| useArray<T>(initialState: T[] | (() => T[])): [T[], ArraySetter<T>] | ||
| ``` | ||
| Hook for creating an array with several setters for ease of use. | ||
| #### `ArraySetter` interface | ||
| `set` - Sets the state, the same you would get with `React.useState`; | ||
| `append: (element: T) => void` - Appends an element to the state | ||
| `prepend: (element: T) => void` - Prepends an element to the state | ||
| `pop: () => T` - Removes and returns the last element from the state | ||
| `shift: () => T` - Removes and returns the first element from the state | ||
| `concat: (elements: T[]) => void` - Concatenates a given array to the state; | ||
| `transform` - Allows you to transform each element of the state, with the same API as `Array.prototype.map` | ||
| `filter` - Like `Array.prototype.filter` | ||
| `reset: () => void` - Resets the state back to the initial value | ||
| `clear: () => void` - Sets the state to `[]` | ||
| ### useToggle | ||
@@ -233,3 +229,6 @@ | ||
| setValue.reset(100); | ||
| setValue.inc(); | ||
| console.log(value); // 96 | ||
| setValue.reset(); | ||
| console.log(value); // 0 | ||
@@ -267,3 +266,3 @@ }; | ||
| console.log(getValue(); // my_value | ||
| console.log(getValue()); // my_value | ||
| console.log(getValueFromResolver()); // 'my_value_from_resolver' | ||
@@ -270,0 +269,0 @@ }; |
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
61746
18.15%163
5.84%269
-0.37%2
100%