Integrating Middleware for Debugging Custom Hooks
Provide an example of integrating middleware into TanStack Store for logging state changes, aiding in debugging custom hooks.
const debugMiddleware = (store) => (next) => (action) => {
console.log('Action type:', action.type);
const result = next(action);
console.log('New state:', store.getState());
return result;
};
This middleware logs the action type and the new state after the action is dispatched. It's useful for debugging to see how actions affect the state.
import { createStore, applyMiddleware } from '@tanstack/store-core';
const initialState = { count: 0 };
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + 1 };
default:
return state;
}
};
const store = createStore({
reducer: counterReducer,
middleware: [debugMiddleware]
});
Sets up a simple TanStack Store with the debugMiddleware integrated. The store manages a simple counter state, incrementing the count with an 'increment' action type.
const useCustomHook = () => {
const [state, dispatch] = useStoreState(store);
const increment = () => {
dispatch({ type: 'increment' });
};
return { state, increment };
};
Defines a custom hook that utilizes the `useStoreState` hook from TanStack Store. This hook exposes a state object and an increment function which dispatches an 'increment' action.