1

I'm calling an api request to update (edit) values in my array of objects. But the issue is i can only see the updated value after page refresh. To see the updated (edited) values instantly i'm trying to insert the updated values to my object locally (Only if the request is executed successfully). My approach is as follows

Action

            .then(res => {
                if (res.data.success === true) {
                    const updatedBillingPlan = {
                        "billingId":data.billingId,
                        "name": data.name,
                        "rateKWh": data.rateKWh,
                        "rateMin": data.rateMin,
                        "rateTransaction": data.rateTransaction
                    }
                    dispatch(updateBillingPlansSuccess(updatedBillingPlan));
                } else {
                    alert("error");
                }
            })

Reducer

            case UPDATE_BILLING_PLANS_SUCCESS:

            let updatedBillingArray = (Here i need to include action.data to billingData )

            return update(state, {
                billingData: updatedBillingArray,
            })

I'm trying to use immutability-helper library.

How would i go about this?

For example when i delete a record, to display the newest array with the deleted record , i'm doing something like this.

           case DELETE_MODAL_SUCCESS:
            let updatedBillingArray = state.billingData.filter(property => property.billingId !== action.data);
            return {
                ...state,
                billingData: updatedBillingArray,
                billingDeleteToast: true
            }

I want to do the same with update as well.

1 Answer 1

1

assuming billingID is unique among the billing plans, you could use that to update the proper element in the array:

        case UPDATE_BILLING_PLANS_SUCCESS:

        let updatedBillingArray = state.billingData.map(bp => if (bp.billingId === action.data.billingId) return action.data else return bp);

        return update(state, {
            ...state,
            billingData: updatedBillingArray,
        })
Sign up to request clarification or add additional context in comments.

2 Comments

My array has several objects. So for example say i edited the 7th object. I just want to update the 7th object with the edited values
then you'd have to send both the updated billing plan and its position to the reducer and then something like: let updatedBillingArray = [...state.billingData]; updatedBillingArray[action.data.position] = action.data.updatedBillingPlan;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.