Russell
Russell

Reputation: 1814

Refactoring javascript code react redux issue

I've code like below. No deep knowledge in javascript. Want to add some product in redux. My reducer initial definition is below

const initState = {
    order: {
        item1: [],
        item2: [],
        item3: [],
      }
    }

To add different items to the cart I'm using below function. Every item will be a list of object

    const addToCart = (state, action) => {
    if (action.payload.service === 'item1') {
        return {
            ...state,
            order: {
                ...state.order,
                item1: [...state.order.item1, action.payload.item]
            }
        }
    } else if (action.payload.service === 'item2') {
        return {
            ...state,
            order: {
                ...state.order,
                item2: [...state.order.item2, action.payload.item]
            }
        }
    }
}

can it be done in a single code dynamically without condition? My order will be like below

order: {
        item1: [{'name': 'name1', 'quantity': 2}, {'name': 'name3', 'quantity': 5}],
        item2: [],
        item3: [],
      }

Upvotes: 0

Views: 70

Answers (1)

Tung Pham
Tung Pham

Reputation: 587

I believe that for you to take out the conditional statement, assuming that the name of the key of the order is the same as the service name from your payload, you can access and assign the key by passing the value from the payload itself. So instead of something like you have in the reducer, you will get something like this:

 const addToCart = (state, action) => {
        return {
            ...state,
            order: {
                ...state.order,
                [action.payload.service]: [...state.order[action.payload.service], action.payload.item]
            }
        }
    }

Upvotes: 3

Related Questions