A hook similar to React's useState
which allows you to also pass promises which resolve to the next state.
Also returns an extra method which extends the current state, synchronously and/or asynchronously. For the current state to be extended, it must first be a non-null value.
Example:
interface State {
foo: string
bar: string
}
const [ state, setState, extendState ] = useAsyncExtendedState<State>({
foo: 'foo',
bar: 'bar'
})
// This works as usual.
setState({ foo: 'Hello', bar: 'World!' })
setState(state => ({ foo: 'Hello', bar: 'World!' }))
// This also works.
const fetchState = () => API.client.get<State>('data').then(response => {
return response.data
// or return (state: State) => {
// return response.data
// }
})
// The state will eventually be set to the asynchronously resolved value.
setState(fetchState())
// Or extend the state immediately.
extendState({ foo: 'Hello' })
extendState(state => ({ bar: 'World!' }))
// Or extend the state asynchronously.
const fetchPartialState = () => API.client.get<Partial<State>>('data').then(response => {
return response.data
// or return (state: State) => {
// return response.data
// }
})
// The state will eventually be extended by the asynchronously resolved value.
extendState(fetchPartialState())
A hook which accepts an asynchronous function (i.e., a function which returns a promise).
Returns a new asynchronous function wrapping the original to be called as necessary,
along with the state of the promise as status
, promise
, value
, error
, cancel()
,
and a reset()
method to reset the state.
Pairs well with the useAsyncExtendedState
hook.
Example:
interface State {
foo: string
bar: string
}
const [ state, setState, extendState ] = useAsyncExtendedState<State>({
foo: 'foo',
bar: 'bar'
})
const read = (id: string) => API.client.get<Partial<State>>(`things/${id}`).then(response => {
return response.data
})
const [ readThingRequest, readThing ] = usePromise(read)
const isPending = readThingRequest.status === 'pending'
return (
<>
<div>
foo: {state.foo}
</div>
<div>
bar: {state.bar}
</div>
<UI.Button onClick={() => extendState(readThing('someId'))} disabled={isPending}>
<span>
{isPending
? 'Reading thing...'
: 'Read thing'
}
</span>
</UI.Button>
<UI.Error>
{readThingRequest.error}
</UI.Error>
</>
)
Generated using TypeDoc
Hooks used throughout the app to simplify state management.