Blog>
Snippets

Creating and Integrating a Product Store with TanStack Store in React

Shows how to create a product store using TanStack Store for managing product data and integrate it into React components.
import { createStore } from '@tanstack/react-store';

// Define the initial state for the store
cconst initialState = {
  products: [],
  isLoading: true,
};

// Create the store using the initial state
export const productStore = createStore({
  initialState,
});
This snippet initializes a product store using TanStack Store with an initial state consisting of an empty products array and a loading state.
import { useEffect } from 'react';
import { useStore } from '@tanstack/react-store';
import { productStore } from './productStore';

export function ProductList() {
  const [state, actions] = useStore(productStore);
  
  useEffect(() => {
    // Simulate fetching products from an API
    setTimeout(() => {
      actions.setState(prevState => ({
        ...prevState,
        products: [{ id: 1, name: 'Product A' }, { id: 2, name: 'Product B' }],
        isLoading: false,
      }));
    }, 1000);
  }, [actions]);
  
  return (
    <div>
      {state.isLoading ? (
        <p>Loading...</p>
      ) : (
        state.products.map(product => (
          <div key={product.id}>{product.name}</div>
        ))
      )}
    </div>
  );
}
This code demonstrates a React component that uses the product store. It simulates fetching products and updating the store state, then renders the list of products accordingly.