Blog>
Snippets

Using TanStack Store with Async Operations

Show how to manage asynchronous operations such as fetching data from an API using TanStack Store, with emphasis on error handling and loading states.
import { createStore } from '@tanstack/react-store';

// Defining the async operation state
const initialState = {
  data: null,
  status: 'idle', // 'loading' | 'success' | 'error'
  error: null
};

// Creating the store
export const store = createStore({
  initialState,
  actions: {
    fetchData: async (state, fetchFunction) => {
      state.status = 'loading';
      try {
        const data = await fetchFunction();
        state.data = data;
        state.status = 'success';
      } catch (error) {
        state.error = error;
        state.status = 'error';
      }
    }
  }
});
This code snippet demonstrates creating a TanStack Store to manage asynchronous operations. The store's initial state includes properties to hold data, a loading status, and any possible error. An `fetchData` action is defined to perform asynchronous operations. It sets the loading state, tries to fetch data using a provided fetch function, and updates the state based on the operation's success or failure, handling errors appropriately.