Appearance
useList
Tracks an array and returns it with a stable set of immutable mutators.
Demo
Usage
tsx
import { useList } from '@reause/shared'
const [list, { push, updateAt, upsert, sort, filter, removeAt, clear, reset }] = useList([1, 2, 3])
push(4) // [1, 2, 3, 4]
updateAt(0, 9) // [9, 2, 3, 4]
upsert(item => item === 2, 7) // replaces the match → [9, 7, 3, 4]; pushes the item when nothing matches
sort((a, b) => b - a) // [9, 7, 4, 3]
filter(item => item > 3) // [9, 7, 4]
removeAt(0) // [7, 4]
clear() // []
reset() // [1, 2, 3]Type Declarations
ts
export type IHookStateInitAction<S> = S | (() => S)
export type IHookStateSetAction<S> = S | ((prevState: S) => S) | (() => S)
export interface ListActions<T> {
set: (newList: IHookStateSetAction<T[]>) => void;
push: (...items: T[]) => void;
updateAt: (index: number, item: T) => void;
insertAt: (index: number, item: T) => void;
update: (predicate: (a: T, b: T) => boolean, newItem: T) => void;
updateFirst: (predicate: (a: T, b: T) => boolean, newItem: T) => void;
upsert: (predicate: (a: T, b: T) => boolean, newItem: T) => void;
sort: (compareFn?: (a: T, b: T) => number) => void;
filter: (callbackFn: (value: T, index?: number, array?: T[]) => boolean, thisArg?: any) => void;
removeAt: (index: number) => void;
remove: (index: number) => void;
clear: () => void;
reset: () => void;
}
export function useList<T>(initialList?: IHookStateInitAction<T[]>): [
T[],
ListActions<T>
]