Updating array in reducer

Viewed 36

i am trying to update state in reducer with a array of objects. Following is what i am doing.

Action.js file

export const apiSuccess = (data, forCust) => {
    return {
        type: ACTIONS.validateSuccess,
        data: data,
        forCust
    };
};

export const apiFailed = (error, forCust) => {
    console.log('pandetail failed', error)
    return {
        type: ACTIONS.ValidateFailed,
        data: error?.details?.data,
        forCust
    };
};

here forCust can be customer or admin

Here is the reducer

const initialState = {
    otherDetails: {},
    individualDetails: [{ forCust: 'customer' }, { forCust: 'admin' }],
};

const reducer = (state = initialState, action = {}) => {
    switch (action.type) {
        case ACTIONS.validateSuccess:
            console.log('Action in reducer', action)
            debugger;
            return {
                ...state,
                otherDetails: action?.data,
                individualDetails: state.individualDetails.map((item) => {
                if(item.forCust === action.forCust){
                    item = action
                }
                return item
                }),
            }
        case ACTIONS.validateFailed:
            return {
                ...state,
                otherDetails: action?.data,
                individualDetails: state.individualDetails.map((item) => {
                    if (item.forCust === action.forCust) {
                        item = action
                    }
                    return item
                }),
            }
        default:
            return state;
    }
};

export default reducer;

Now, when action is dispatched it dispatches with success and other parameter which is forCust to check if the dispatched action is for admin or customer. Now i have two fields in the same component but different parameters which calls the action(admin/customer). If the validateSuccess with customer is called i am trying to update customer details in individualDetails array and if admin is called i am trying to update only the admin state array object. Now, what happens is that i am not able to maintain the old state ie when customer changes and admin details is there, it updated the whole array, not only the customer. Also if somehow one of them get failed, failed action is dispatched and then update the array corresponding to the forCust field.

any help will be appreciated.

0 Answers
Related