Blog>
Snippets

Implementing Selectors for Computed States

Illustrate how to create and use selectors with TanStack Store for deriving computed states from the store's state.
import { createStore, createSelector } from '@tanstack/react-store';

// Initial state
const initialState = {
  items: [
    { id: 1, name: 'Apple', price: 0.99, quantity: 3 },
    { id: 2, name: 'Banana', price: 0.5, quantity: 5 },
    { id: 3, name: 'Carrot', price: 0.25, quantity: 4 }
  ]
};

// Creating the store with initial state
const store = createStore({
  initialState
});
This piece of code imports necessary functions from '@tanstack/react-store' and establishes the initial state of the store with a simple list of items. Then, it creates the store using this initial state.
// Selector for computing total price of items in the cart
const selectTotalPrice = createSelector(
  (state) => state.items,
  (items) => items.reduce((total, item) => total + item.price * item.quantity, 0)
);
This code creates a selector named `selectTotalPrice`. It calculates the total price of items in the cart by first accessing the `items` from the state and then applying a reduce function to sum up the product of each item's price and quantity.
const totalPrice = store.select(selectTotalPrice);
console.log(`Total Price: $${totalPrice}`);
The store's `select` method is used with the previously defined `selectTotalPrice` selector to compute the total price based on the current state. The computed total price is then logged to the console.