0.2.1 • Published 2 months ago

react-state-hooks v0.2.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

Hooks

useAsyncState

// useAsyncState<T>(getter: () => Promise<T>)

// Example:
const [user, setUser, { error, isLoading, revalidate }] = useAsyncState(getUser)

async function getUser() {
    return { name: 'Richard' }
}

// Re-run getter
revalidate()

useDependentState

// useDependentState<T>(setter: (current?: T) => T, deps: any[])

// Example:
const { user } = useAuth();

const [value, setValue] = useDependentState(() => {
  return {
    userId: user.id,
    page: 1,
  }
}, [user]);

// Manual change state
setValue((current) => {
  return {
    ...current,
    page: 2
  }
});

useHistoryState

// useHistoryState<T>(initialState?: T, length: number = 10)

// Example:
const [value, setValue, { history, rollback }] = useHistoryState(0)

// Rollback
setValue(2) // value is now 2
rollback() // value is now 0

useListState

// useListState<T>(initialState?: T[])

// Example:
const [list, { set, push, insert, remove, update, clear, sort, filter }] = useListState({ name: 'Richard' })

// Reset
set([1, 2])

// Add
push(3, 4, 5, 6)

// Insert at index
insert(0, 'Hello')

// Remove
remove(0) // by index
remove((item) => item.id === 5) // by handler

// Update
update(0, { name: 'Richard' }) // by index
update((item) => item.id === 5, { name: 'Richard' }) // by handler

// Clear
clear()

// Sort
sort()
sort((a, b) => a.age - b.age)

// Filter
filter((item) => item.age > 21)

useNumberState

// useNumberState(initialState?: number, options?: { min?: number, max?: number, step?: number })

// Example:
const [number, setNumber, { inc, dec }] = useNumberState(0)

// Increment
inc(10)

// Decrement
dec(10)

// Options
const [...] = useNumberState(0, { min: 2, max: 10, step: 2 })

useObjectState

// useObjectState<T>(initialState?: T)

// Example:
const [obj, updateObj, resetObj] = useObjectState({ name: 'Richard' })

// Update
updateObj({ age: 21 });

// Reset
resetObj({});

usePropState

// usePropState<T>(prop: T | undefined, initialState?: T | (() => T))

// Example:
const [name, setName] = usePropState(props.name, 'Richard')

useStoreState

// useStoreState<T>(key: string, initialState?: T | (() => T))

// Example:
const [name, setName] = useStoreState('user.name', 'Richard')

useToggleState

// useToggleState(initialState?: boolean)

// Example:
const [isVisible, toggleIsVisible] = useToggleState(false)
0.2.1

2 months ago

0.2.0

2 months ago

0.1.9

3 months ago

0.1.8

3 months ago

0.1.7

5 months ago

0.1.6

5 months ago

0.1.4

6 months ago

0.1.3

6 months ago

0.1.2

6 months ago

0.1.1

6 months ago

0.1.0

6 months ago

0.0.8

6 months ago

0.0.7

6 months ago

0.0.3

6 months ago

0.0.2

6 months ago

0.0.1

6 months ago