Blog>
Snippets

Managing Asynchronous Operations

Demonstrate handling an API call within TanStack Store actions, using async/await syntax to fetch data and update the store state upon request completion.
import { createStore, action } from 'easy-peasy';

const storeModel = {
  items: [], // Initial state of items
  fetchItems: action(async (state) => {
    state.items = await fetch('https://api.example.com/items')
      .then(res => res.json())
      .catch(err => console.error('Fetching items failed:', err));
  })
};

const store = createStore(storeModel);
This code snippet demonstrates how to handle an API call within an action in a store model, using TanStack Store (formerly known as easy-peasy), which is an abstraction built on top of Redux. The 'fetchItems' action is asynchronous, utilizing the async/await syntax to fetch data from a hypothetical API endpoint. Upon completion of the request, the fetched data is assigned to the 'items' state. Error handling is also demonstrated through a catch block, logging any potential errors encountered during the fetch operation.