Blog>
Snippets

Managing Server State with TanStack Store

Show how to manage server state by fetching data from an API and caching it with TanStack Store, including the handling of loading states and errors.
import { createStore } from 'tanstack-store';
Firstly, import the createStore method from tanstack-store to create a new store.
const initialState = {
  data: null,
  loading: false,
  error: null
};
Define the initial state of our store, which includes data for storing the fetched data, loading for indicating the loading state, and error for storing any potential errors.
const fetchApiData = async () => {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) throw new Error('Network response was not ok.');
    return await response.json();
  } catch (error) {
    throw error;
  }
};
Define an asynchronous function to fetch data from an API. It handles both successful responses by parsing the JSON, and errors by throwing them.
const useServerStateStore = createStore((set) => ({
  ...initialState,
  fetchData: async () => {
    set(state => ({ ...state, loading: true }));
    try {
      const data = await fetchApiData();
      set(state => ({ ...state, data, loading: false }));
    } catch (error) {
      set(state => ({ ...state, error, loading: false }));
    }
  }
}));
Create the server state store using the createStore method. It uses the initial state and defines an asynchronous method fetchData to fetch data from the API, update the state accordingly, and handles loading and errors.
// Usage example within a component
const { data, loading, error, fetchData } = useServerStateStore(state => state);
if (loading) console.log('Loading...');
else if (error) console.error('Error:', error);
else console.log('Data:', data);
fetchData();
Example usage of the store within a component. It destructures the necessary states and actions from the store. Calls fetchData to fetch the data, and handles the rendering logic based on the current state.