Blog>
Snippets

Implementing Middleware in TanStack Store

Detail the process of creating and applying middleware in TanStack Store for logging actions, showcasing the implementation and effect on dispatched actions.
import { createStore } from 'tanstack-store';

// Define a simple logger middleware
const loggerMiddleware = store => next => action => {
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  return result
};
This piece creates a logger middleware using the createStore method from tanstack-store. The middleware logs the action being dispatched and the next state of the store after the action is processed.
const initialState = { counter: 0 };

// Action types
const INCREMENT = 'INCREMENT';

// Reducer function
function counterReducer(state = initialState, action) {
  switch (action.type) {
    case INCREMENT:
      return { ...state, counter: state.counter + 1 };
    default:
      return state;
  }
}
Defines the initial state and a simple reducer function for a counter, with an action to increment the counter.
const store = createStore({
  reducer: counterReducer,
  middleware: [loggerMiddleware]
});

// Dispatch an action
store.dispatch({ type: INCREMENT });
Creates a store with the counterReducer and applies the loggerMiddleware. Then, dispatches an INCREMENT action to demonstrate the middleware's logging effect.