All files / useSetState index.tsx

100% Statements 51/51
100% Branches 11/11
100% Functions 1/1
100% Lines 51/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 521x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 4x 4x 3x 4x 1x 1x 9x 9x 3x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 9x 9x  
import { useState } from 'react'
import { ObjectType } from 'abandonjs'
import { isEffectArray, isNumber, isString } from 'asura-eye'
 
/**
 * @title UseSetState<T>
 * @description 类似 setState 的使用
 * @param 0 state {T} 状态
 * @param 1 setState {T} 修改状态
 * @param 2 resetState {T} 恢复默认状态
 */
export type UseSetState<T extends ObjectType> = readonly [
	Partial<T>,
	(patch: Partial<T> | ((prevState: Partial<T>) => Partial<T>), cover?: boolean) => void,
	(props?: (string | number)[]) => void,
]
 
/**
 * @title useSetState<T> 
 * @description 类似 setState 的使用
 * @param initialState {T} 默认值
 * @returns {UseSetState}
 */
export function useSetState<T extends ObjectType>(initialState: T = {} as T)
	: UseSetState<T> {
 
	const [state, setState] = useState<Partial<T>>(initialState)
	return [
		state,
		(patch: Partial<T> | ((prevState: Partial<T>) => Partial<T>), cover = false): void => {
			const coverState: Partial<T> = typeof patch === 'function' ? patch(state) : patch
			if (cover) {
				setState(coverState)
			} else {
				setState({ ...state, ...coverState })
			}
		},
		(props?: (string | number)[]): void => {
			if (isEffectArray(props)) {
				const newState: Partial<T> = { ...state }
				props.forEach((prop) => {
					if (isString(prop) || isNumber(prop))
						(newState as ObjectType)[prop] = initialState[prop]
				})
				setState(newState as T)
				return
			}
			setState(initialState)
		}
	] as const
}