Below is my code, whatever action i dispatch using the below reducer, dispatch is called twice. I have read that reducers must be pure functions and no side effects or api calls to be made from a reducer. Else this behaviour is expected. What am i missing? Is my function impure?
const modalInitialState = {
Id: "",
Name: "",
PhoneNumber: "",
Email: "",
IsOpen: false,
Header: null,
Mode: null,
};
const modalActions = {
ADD: "ADD",
UPDATE: "UPDATE",
CANCEL: "CANCEL",
ON_CHANGE: "ON_CHANGE",
OPEN_AS_ADD: "OPEN_AS_ADD",
OPEN_AS_UPDATE: "OPEN_AS_UPDATE",
};
const modalReducer = (state, action) => {
switch (action.type) {
case modalActions.CANCEL:
return modalInitialState;
break;
case modalActions.ON_CHANGE:
switch (action.id.toLowerCase()) {
case "name":
return { ...state, Name: action.val };
break;
case "phonenumber":
return { ...state, PhoneNumber: action.val };
break;
case "email":
return { ...state, Email: action.val };
break;
}
break;
case modalActions.OPEN_AS_ADD:
return { ...state, IsOpen: true, Header: "Add", Mode: "Add" };
break;
case modalActions.OPEN_AS_UPDATE:
return { ...state, IsOpen: true, Header: "Update", Mode: "Update" };
break;
case modalActions.CANCEL:
return { ...state, IsOpen: false };
break;
case modalActions.ADD:
return modalInitialState;
break;
case modalActions.UPDATE:
return modalInitialState;
break;
default:
return state;
}
};
const [modalState, modalDispatch] = useReducer(
modalReducer,
modalInitialState
);
const OnChangeHandler = (event) => {
modalDispatch({
type: modalActions.ON_CHANGE,
id: event.target.id,
val: event.target.value,
});
};