Blog>
Snippets

Using Middleware for Async Data Handling with TanStack Store

Illustrate the usage of middleware in TanStack Store for managing asynchronous operations such as API calls, including error handling and loading states.
import { createStore } from 'tanstack-store-react';

// Middleware to handle async operations
const asyncMiddleware = store => next => async action => {
  if (typeof action === 'function') {
    store.setState({ loading: true });
    try {
      const result = await action(store.getState());
      next(result);
    } catch (error) {
      store.setState({ error });
    } finally {
      store.setState({ loading: false });
    }
  } else {
    next(action);
  }
};
This defines a middleware function for TanStack Store that checks if the dispatched action is a function (indicating an async operation). It sets the loading state before executing the action, handles the result or error, and finally resets the loading state.
const store = createStore({
  initialState: { userData: {}, loading: false, error: null },
  actions: {
    fetchUserData: async (state) => {
      const response = await fetch('https://api.example.com/users');
      const data = await response.json();
      return { userData: data };
    }
  }
}).addMiddleware(asyncMiddleware);
This snippet sets up the store with an initial state and adds our asyncMiddleware to handle asynchronous actions. The `fetchUserData` action is defined for fetching user data asynchronously.