Blog>
Snippets

Implementing Asynchronous Actions in TanStack Store

Outline how to implement asynchronous actions within TanStack Store, such as loading data asynchronously and updating the store state upon completion.
import { createStore } from 'tanstack-store-react';

// Define the store
const userStore = createStore({
  initialState: {
    users: [],
    loading: false,
    error: null
  },
  actions: {
    fetchUsers: async (state) => {
      state.loading = true;
      try {
        const response = await fetch('https://api.example.com/users');
        const users = await response.json();
        state.users = users;
        state.error = null;
      } catch (error) {
        state.error = error;
      } finally {
        state.loading = false;
      }
    }
  }
});
This code snippet demonstrates the setup of an asynchronous action within TanStack Store to fetch user data from an API. It initializes a `userStore` with `users`, `loading`, and `error` state properties. The action `fetchUsers` sets the loading state before making the fetch call, updates the `users` state with the fetched data, handles any error by setting the `error` state, and finally resets the loading state.
const { useStore, useStoreActions } = userStore;

function UserComponent() {
  const users = useStore((state) => state.users);
  const loading = useStore((state) => state.loading);
  const error = useStore((state) => state.error);
  const fetchUsers = useStoreActions((actions) => actions.fetchUsers);

  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {users.map((user) => (
        <div key={user.id}>{user.name}</div>
      ))}
    </div>
  );
}
This React component utilizes the `useStore` and `useStoreActions` hooks from our TanStack Store `userStore` to manage the state and actions. It fetches the user data on component mount using the `fetchUsers` action. It also handles the loading and error states, displaying appropriate messages, and renders the list of users when the fetch operation is complete.