Blog>
Snippets

Async Operations with TanStack Store

Provide an example of handling asynchronous operations in TanStack Store actions, such as fetching data from an API and updating the store state.
import { createStore } from 'tanstack-store-react';

// Define initial state
const initialState = { userData: null, loading: false, error: null };

// Create a store with initialState
const userStore = createStore({
  initialState,
  actions: {
    fetchUserData: async (state) => {
      try {
        // Indicate loading state
        state.loading = true;
        // Fetch data from an API
        const response = await fetch('https://api.example.com/user');
        const data = await response.json();
        // Update store state with fetched data
        state.userData = data;
        state.error = null;
      } catch (error) {
        // Handle error
        state.error = error;
      } finally {
        // Reset loading state
        state.loading = false;
      }
    }
  },
});

// Export the store for use in your application
export default userStore;
This code snippet demonstrates setting up an asynchronous action within a TanStack Store to fetch user data from an API. It starts by importing `createStore` from 'tanstack-store-react' and defining the initial state. A store named `userStore` is created with a `fetchUserData` action that handles the asynchronous operation. The action tries to fetch user data, updates the store state with the fetched data if successful, or sets the error in the state if it encounters an error. It ensures to toggle the loading state before and after the fetch operation. Finally, the store is exported for use in the application.