I am trying to store data from my form component to my store. But when i try to dispatch the action and return the action payload into the state, getting an error which is,
TypeError: state.users is undefined
that action reducer is
export const addUserReducer = (state = { users: [] }, action) => {
switch (action.type) {
case "ADD_USER_REQUEST":
return {
loading: true,
};
case "ADD_USER_SUCCESS":
return {
...state,
users: [...state.users, action.payload],
};
default:
return state;
}
};
Redux store for the app is,
import { combineReducers, createStore, applyMiddleware } from "redux";
import { addUserReducer } from "./Reducers/addUserReducer";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
const finalReducer = combineReducers({
addUserReducer: addUserReducer,
});
const composeEnhancers = composeWithDevTools({
// Specify here name, actionsBlacklist, actionsCreators and other options
});
const usersFromStorage = localStorage.getItem("Users")
? JSON.parse(localStorage.getItem("Users"))
: [];
console.log(usersFromStorage);
const initialState = {
addUserReducer: {
users: usersFromStorage,
},
};
const store = createStore(
finalReducer,
initialState,
composeEnhancers(applyMiddleware(thunk))
);
export default store;
I have tried to solve the issue by using many methods but don't know yet that where is the main problem.
In the first case of your switch you should return the other part of the state as well: