DEV Community

SWAPNIL AHMMED SHISHIR
SWAPNIL AHMMED SHISHIR

Posted on

start redux basic

const { createStore } = require("redux");

// Constants
const INCREMENT = "INCREMENT";
const DECREMENT = "DECREMENT";
const ADD_USER = "ADD_USER";
const REMOVE_USER = "REMOVE_USER";

// Initial State
const initaialCounterState = {
count: 0,
user: [{ name: "swapnil" }],
};

// Action Creators
const incrementCounterAction = () => ({ type: INCREMENT });
const decrementCounterAction = () => ({ type: DECREMENT });
const addUser = () => ({
type: ADD_USER,
payload: { name: "shishir" },
});
const removeUser = () => ({
type: REMOVE_USER,
payload: { id1: "swapnil" },
});

// Reducer
const counterReducer = (state = initaialCounterState, action) => {
switch (action.type) {
case INCREMENT:
return { ...state, count: state.count + 1 };
case DECREMENT:
return { ...state, count: state.count - 1 };
default:
return state; // ✅ Always return state
}
};

// Store
const store = createStore(counterReducer);

// Subscribe to store changes
store.subscribe(() => {
console.log("Updated State:", store.getState());
});

// Dispatch actions
store.dispatch(incrementCounterAction()); // should increase count

Top comments (0)