Blog>
Snippets

Using Middleware for Logging Actions

Explain how to integrate middleware in TanStack Store for logging actions, showcasing a simple logger middleware that logs all actions dispatched to the store.
import { createStore } from 'tanstack-store';

// Define a logger middleware
const loggerMiddleware = (store) => (next) => (action) => {
  console.log('dispatching', action);
  let result = next(action);
  console.log('next state', store.getState());
  return result;
};
This code snippet demonstrates how to define a simple logger middleware using TanStack Store. The middleware logs the action being dispatched and the next state of the store after the action is processed.
const store = createStore({
  initialState: {},
  reducers: {},
  middleware: [loggerMiddleware]
});
This code integrates the logger middleware into the store. It creates a new TanStack Store instance with an initial state, reducers, and includes the logger middleware defined earlier in the middleware array.