Blog>
Snippets

Managing Asynchronous Operations with TanStack Store

Demonstrate how to manage asynchronous actions such as API calls within TanStack Store, using its lightweight approach to handle state updates upon data fetch completion.
import { createStore, action } from '@tanstack/store-react';

// Define the initial state
const initialState = {
  posts: [],
  loading: false,
  error: null
};

// Create a store with the initial state
export const postsStore = createStore({
  initialState,
  actions: {
    fetchPostsStart: action((state) => {
      state.loading = true;
      state.error = null;
    }),
    fetchPostsSuccess: action((state, payload) => {
      state.posts = payload;
      state.loading = false;
    }),
    fetchPostsFailure: action((state, payload) => {
      state.error = payload;
      state.loading = false;
    })
  }
});
This code snippet demonstrates how to create a store for managing posts using @tanstack/store-react. The store starts with an initial state indicating that no posts have been fetched yet. It defines actions for handling the start of a fetch operation, a successful fetch where posts data is set, and a failure, where an error is recorded.
import { postsStore } from './postsStore';

// Function to fetch posts from an API
export async function fetchPosts() {
  postsStore.actions.fetchPostsStart();
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    const data = await response.json();
    postsStore.actions.fetchPostsSuccess(data);
  } catch (error) {
    postsStore.actions.fetchPostsFailure(error.toString());
  }
}
This code snippet demonstrates how to use the previously defined store to manage asynchronous API calls for fetching posts. The `fetchPosts` function dispatches actions to update the store's state based on the outcome of the fetch operation: it indicates when the fetch starts, updates the store with fetched data on success, or records an error on failure.