import { HANDLE_CHANGE_EVENT, RESET_FORM, HANDLE_SUBMIT_EVENT, ADD_HOBBY, REMOVE_HOBBY, REMOVE_ITEM, EDIT_ITEM, SUBMIT_HANDLER_EDIT } from "../actionTypes/actionTypes"; const list = [ { id: 1, editable: true, firstName: "Tony", lastName: "Montana", age: 50, hobby: ["drugs", "guns"] } ]; const initialValue = { list: list, editableForm: false, item: { editable: false, firstName: "", lastName: "", age: "", hobby: [ { id: Math.random() .toString() .substr(2, 100), value: "" } ] }, updateObject: {} }; export default (state = initialValue, action) => { switch (action.type) { case HANDLE_CHANGE_EVENT: { const { name, value, checked, type, id } = action.payload.target; if (name === "hobby") { return { ...state, item: { ...state.item, hobby: state.item.hobby.map(el => (el.id === id ? { ...el, value } : el)) } }; } return { ...state, item: { ...state.item, [name]: type === "checkbox" ? checked : value } }; } case RESET_FORM: { return { ...state, editableForm: initialValue.editableForm, item: initialValue.item }; } case HANDLE_SUBMIT_EVENT: { return { ...state, list: state.list.concat({ ...state.item, id: Math.random() .toString() .substr(2, 100), hobby: state.item.hobby.filter(el => el.value).map(el => el.value) }), editableForm: initialValue.editableForm, item: initialValue.item }; } case ADD_HOBBY: { return { ...state, item: { ...state.item, hobby: state.item.hobby.concat({ id: Math.random() .toString() .substr(2, 100), value: "" }) } }; } case REMOVE_HOBBY: { return { ...state, item: { ...state.item, hobby: state.item.hobby.filter(el => el.id !== action.payload) } }; } case REMOVE_ITEM: { return { ...state, list: state.list.filter(el => el.id !== action.payload) }; } case EDIT_ITEM: { const item = state.list.find(el => el.id === action.payload); return { ...state, item: { ...item, hobby: item.hobby.map(el => ({ id: Math.random() .toString() .substr(2, 100), value: el })) }, editableForm: true }; } case SUBMIT_HANDLER_EDIT: { return { ...state, list: state.list.map(el => el.id === state.item.id ? { ...state.item, hobby: state.item.hobby.filter(el => el.value).map(el => el.value) } : el ), editableForm: initialValue.editableForm, item: initialValue.item }; } case "@@redux-form/CHANGE": { if (action.meta.form === "redux-form") { console.log("sdsasda"); return { ...state, updateObject: { ...state.updateObject, [action.meta.field]: action.payload } }; } return state; } default: return state; } };