@reatom/async
withAsync
Extension that adds async state tracking to atoms or actions that return promises. Manages pending state, errors, and provides lifecycle actions for async operations.
This extension preserves Reatom context across async operations, ensuring that the async operation’s results properly update Reatom state.
Example
// Basic usage with an action:const fetchUser = action(async (userId: string) => { const response = await wrap(fetch(`/api/users/${userId}`)) return await wrap(response.json())}, 'fetchUser').extend(withAsync())
// Can then access:fetchUser.error() // → latest error if anyfetchUser.ready() // → are all operations complete?withAsyncData
Extension that adds async data management to atoms or actions that return promises.
Creates a properly typed data atom that stores the results of successful async operations. Includes all features of withAsync and withAbort for complete async handling.
Extension that adds async data management to atoms or actions that return promises.
This overload uses the payload type as the state type with a specified initial value. Useful when you know the shape of the data that will be fetched.
Extension that adds async data management to atoms or actions that return promises.
This overload allows specifying a completely custom state type with an initial value. The resolved payload will be merged with the state without custom mapping.
Extension that adds async data management to atoms or actions that return promises.
This overload provides full control with a custom state type and payload mapping function. Allows complete transformation of the payload into the desired state format.
Implementation of the withAsyncData extension.
Example
// Basic usage with a computed for data fetching:const userId = atom('1', 'userId')
// Create a computed that fetches data when userId changesconst userData = computed(async () => { const id = userId() const response = await wrap(fetch(`/api/users/${id}`)) if (!response.ok) throw new Error('Failed to fetch user') return await wrap(response.json())}, 'userData').extend(withAsyncData())
// Access the fetched data and loading states:userData.data() // → the fetched user datauserData.error() // → error if fetch faileduserData.ready() // → false while loading, true when complete