Blog>
Snippets

Managing Asynchronous Actions with TanStack Store

Provide an example of handling asynchronous actions like API calls within TanStack Store, including state updates upon action completion.
import { createStore, action } from '@tanstack/store';
Import createStore and action from @tanstack/store to create the store and define actions.
const initialState = { data: null, loading: false, error: null };
Define the initial state of the store, including data, loading status, and error information.
const fetchData = async () => { return fetch('https://api.example.com/data').then(res => res.json()); };
Define an asynchronous function fetchData to fetch data from an API.
const store = createStore({ id: 'dataStore', initialState, actions: { setData: action((state, payload) => { state.data = payload; state.loading = false; }), setLoading: action((state, payload) => { state.loading = payload; }), setError: action((state, payload) => { state.error = payload; state.loading = false; }), fetchData: action(async (state) => { state.loading = true; try { const data = await fetchData(); store.dispatch.actions.setData(data); } catch (error) { store.dispatch.actions.setError(error); } }) } });
Create the store with an initial state, actions for updating the state, and an asynchronous fetchData action for making the API call and updating the store accordingly.
store.dispatch.actions.fetchData();
Invoke the fetchData action to load data from the API into the store.