Package @reatom/extensions
@reatom/extensions
Interfaces
AbortExt
Defined in: withAbort.ts:10
Extended by
Properties
abort
abort:
Action<[any]>
Defined in: withAbort.ts:11
DynamicSubscriptionExt
Defined in: withDynamicSubscription.ts:9
This interface improve .subscribe method behavior by relying it on
abortVar. It performs unsubscribe automatically, when abort will occur.
SuspenseRecord
Defined in: withSuspense.ts:9
Internal suspense cache record tracking promise state. Do not use it directly, only for libraries!
Properties
kind
kind:
"fulfilled"|"rejected"|"pending"
Defined in: withSuspense.ts:10
value
value:
any
Defined in: withSuspense.ts:11
Type Aliases
SuspenseExt<State>
SuspenseExt<
State> =object
Defined in: withSuspense.ts:73
Extension type that adds a suspended computed atom to track resolved values
from async atoms.
Type Parameters
State
State
Properties
suspended
suspended:
Computed<Awaited<State>>
Defined in: withSuspense.ts:74
Variables
SUSPENSE
SUSPENSE:
WeakMap<Promise<any>,SuspenseRecord>
Defined in: withSuspense.ts:18
Internal suspense cache mapping promises to their settlement state. Do not use it directly, only for libraries!
Functions
addCallHook()
addCallHook<
Target>(target,cb):Unsubscribe
Defined in: withChangeHook.ts:84
Type Parameters
Target
Target extends Action<any[], any>
Parameters
target
Target
cb
(payload, params) => void
Returns
addChangeHook()
addChangeHook<
T>(target,cb):Unsubscribe
Defined in: withChangeHook.ts:35
Type Parameters
T
T extends AtomLike<any, any[], any>
Parameters
target
T
cb
(state, prevState?) => void
Returns
isInit()
isInit():
boolean
Defined in: withInit.ts:22
Checks if the current execution context is within the initialization of the current atom.
Returns
boolean
True if currently in the initialization phase, false otherwise
Example
const search = atom('', 'search').extend(withSearchParams('search')) const page = atom(1, 'page').extend( withSearchParams('page'), withComputed((state) => { search() // subscribe to the search changes // do NOT drop the persisted state on init return isInit() ? state : 1 }), )settled()
settled<
Result,Fallback>(promise,fallback?):Result|Fallback
Defined in: withSuspense.ts:40
Checks if a promise is settled and returns its value or fallback. If the promise is fulfilled, returns the resolved value. If the promise is rejected, throws the error. If the promise is pending, returns the fallback value (defaults to undefined).
Uses an internal WeakMap cache to track promise states across calls.
Type Parameters
Result
Result
Fallback
Fallback = undefined
Parameters
promise
The promise or synchronous value to check
Result | Promise<Result>
fallback?
Fallback
The value to return if the promise is still pending
Returns
Result | Fallback
The resolved value if fulfilled, throws if rejected, or fallback if pending
Example
;```ts const promise = Promise.resolve(42) await promise const value = settled(promise) // 42
***
### suspense()
> **suspense**\<`State`\>(`target`): `Awaited`\<`State`\>
Defined in: withSuspense.ts:199
Helper function to access the suspended value of an atom. Automaticallyapplies `withSuspense()` extension if the atom doesn't already have it.
This function:
- Returns the resolved value if the promise is fulfilled- Throws the promise if it's still pending (for Suspense boundaries)- Throws the error if the promise is rejected
#### Type Parameters
##### State
`State`
#### Parameters
##### target
[`AtomLike`](core.md#atomlike)\<`State`\>
#### Returns
`Awaited`\<`State`\>
#### Remarks
If `withSuspense` is already applied with different `preserve` options, thebehavior may be inconsistent. Consider applying `withSuspense()` explicitlyto control options.
#### Example
;```tsconst data = computed(async () => { const response = await fetch('/api/data') return response.json()}, 'data')
// Automatically applies withSuspense() and returns suspended valueconst result = computed(() => { try { return suspense(data) // throws promise if pending } catch (promise) { if (promise instanceof Promise) { // Handle pending state return undefined } throw promise // Re-throw errors }}, 'result')@param target - The atom to get the suspended value from
@returns The resolved value (Awaited
withAbort()
withAbort(
strategy):AssignerExt<AbortExt>
Defined in: withAbort.ts:14
Parameters
strategy
"last-in-win" | "first-in-win"
Returns
withCallHook()
withCallHook<
Target>(cb):Ext<Target>
Defined in: withChangeHook.ts:50
Type Parameters
Target
Target extends Action<any[], any>
Parameters
cb
(payload, params) => void
Returns
Ext<Target>
withChangeHook()
withChangeHook<
Target>(cb):Ext<Target>
Defined in: withChangeHook.ts:5
Type Parameters
Target
Target extends AtomLike<any, any[], any>
Parameters
cb
(state, prevState) => void
Returns
Ext<Target>
withComputed()
withComputed<
Target>(computed,options?):Ext<Target>
Defined in: withComputed.ts:25
A middleware extension that enhances an atom with computed capabilities.
Type Parameters
Target
Target extends AtomLike<any, any[], any>
The target atom or action type to be extended with computed functionality.
Parameters
computed
(state) => AtomState<Target>
A function that computes the new state based on the current state.
options?
Configuration options. Default is {}
tail?
boolean = true
Determines the order of the passed
computed calling. ATTENTION: use false only for computed with fixed size
of dependencies. Default is true
Returns
Ext<Target>
The extended atom or action with computed functionality.
withConnectHook()
withConnectHook<
Target>(cb):Ext<Target>
Defined in: withConnectHook.ts:10
Type Parameters
Target
Target extends AtomLike<any, any[], any>
Parameters
cb
(target) => void | Unsubscribe | Promise<void | Unsubscribe>
Returns
Ext<Target>
withDisconnectHook()
withDisconnectHook<
Target>(cb):Ext<Target>
Defined in: withConnectHook.ts:38
Type Parameters
Target
Target extends AtomLike<any, any[], any>
Parameters
cb
(target) => void
Returns
Ext<Target>
withDynamicSubscription()
withDynamicSubscription<
Target>(): (target) =>Target&DynamicSubscriptionExt
Defined in: withDynamicSubscription.ts:12
Type Parameters
Target
Target extends AtomLike<any, any[], any>
Returns
(
target):Target&DynamicSubscriptionExt
Parameters
target
Target
Returns
Target & DynamicSubscriptionExt
withInit()
withInit<
Target>(init):Ext<Target>
Defined in: withInit.ts:57
Define dynamically computed initial value for an atom.
Typically, you can use just an init callback in atom first argument:
atom(() => new Date()). But if you need to add initial callback after the
atom creation, so there this extensions is useful.
Type Parameters
Target
Target extends AtomLike<any, any[], any>
The atom type that extends AtomLike
Parameters
init
The initial value or a function that returns the initial value based on current state
AtomState<Target> | (state) => AtomState<Target>
Returns
Ext<Target>
An extension that can be applied to an atom
Examples
const something = reatomSomething().extend( withInit((initState) => ({ ...initState, ...additions })), )const myData = atom(null, 'myData') if (meta.env.TEST) { myData.extend(withInit(mockData)) }withInitHook()
withInitHook<
Target>(hook):Ext<Target>
Defined in: withInit.ts:95
Extension that runs the passed hook when the atom is initialized.
Type Parameters
Target
Target extends AtomLike<any, any[], any>
The atom type that extends AtomLike
Parameters
hook
(initState) => any
A function to be called with the initial state during initialization
Returns
Ext<Target>
An extension that can be applied to an atom
Example
const userAtom = atom({ id: 1, name: 'John' }).extend( withInitHook((initState) => { // Perform any setup logic here analytics.track('user_loaded', initState) }), )withMemo()
withMemo<
Target>(isEqual):Ext<Target>
Defined in: withMemo.ts:6
Type Parameters
Target
Target extends AtomLike<any, any[], any>
Parameters
isEqual
(prevState, nextState) => boolean
Returns
Ext<Target>
withSuspense()
withSuspense<
Target>(__namedParameters):Ext<Target,SuspenseExt<AtomState<Target>>>
Defined in: withSuspense.ts:116
Extension that adds suspense support to async atoms. Creates a suspended
computed atom that tracks the resolved value of promises and throws the
promise when pending (for React Suspense compatibility).
The suspended atom will:
- Return the resolved value immediately if the promise is already fulfilled
- Throw the promise if it’s still pending (allowing Suspense boundaries to catch it)
- Propagate errors if the promise is rejected
- Automatically update when the promise resolves
Type Parameters
Target
Target extends AtomLike<any, any[], any> & Partial<SuspenseExt<AtomState<Target>>>
Parameters
__namedParameters
preserve?
boolean = false
Returns
Ext<Target, SuspenseExt<AtomState<Target>>>
Example
;```ts const data = computed(async () => { const response = await fetch(‘/api/data’) return response.json() }, ‘data’).extend(withSuspense())
// Subscribe to resolved values subscribe(data.suspended, (value) => { console.log(‘Resolved:’, value) })
// Use in React component with Suspense function Component() { const value = useAtom(data.suspended) // throws promise if pending return
@param options - Configuration options@param options.preserve - If true, preserves the previous state whensuspending instead of throwing immediately. Useful for preventingflickering in UI.@returns An extension that adds the `suspended` computed atom
***
### withSuspenseRetry()
> **withSuspenseRetry**\<`T`\>(): [`Ext`](core.md#ext)\<`T`\>
Defined in: withSuspenseRetry.ts:28
Creates a mixin that retries an async action when it fails coz of asuspension
This mixin wraps an async action to automatically retry it when a Promise isthrown, which indicates a suspension. It will keep retrying until the actioncompletes successfully or throws a non-Promise error.
⚠️ Be careful with non-idempotent operations inside the action body, as theymay be executed multiple times during retries. It's recommended to carefullyplan the execution logic to handle potential retries safely.
#### Type Parameters
##### T
`T` *extends* [`Action`](core.md#action)\<`unknown`[], `Promise`\<`unknown`\>\>
#### Returns
[`Ext`](core.md#ext)\<`T`\>
The same passed action
#### Example
```tsconst fetchUserBooks = action(async () => { const id = user().id // `user` is a suspended atom const response = await fetch(`/api/users/${id}/books`) return response.json()}).extend(withSuspenseRetry())