npm install --save redux
import redux from 'redux';
const reducer = (state = { counter: 0 }, action) => {
switch (action.type) {
case 'INCREMENT':
return { counter: state.counter + 1 };
case 'DECREMENT':
return { counter: state.counter - 1 };
default:
return state;
}
};
const subscriber = () => {
const latestState = store.getState();
console.log(latestState);
};
const store = redux.createStore(reducer);
store.subscribe(subscriber);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'DECREMENT' });
Output:
{ counter: 1 }
{ counter: 2 }
{ counter: 1 }
{ counter: 0 }