Palvia Oktopus
Palvia Oktopus

Reputation: 85

Reducing amount of code in Redux reducers

I'm beginner in Redux and I was doing just fine until I started implementing new things, that are kinda repetetive.

I am creating a store that includes a lot of booleans. Default state looks like this:

 const inventoryDefaultState = {
    items: {
        boltcutters: false,
        knife: false,
        spoon: false
    }
}

And so on. Is there a way I can combine it all into one reducer instead of basically repeating this case:

const inventoryReducer = (state = inventoryDefaultState, action) => {
    switch (action.type) {
        case 'PICK_UP_BOLTCUTTERS':
            return {
                ...state,
                items: {
                    ...state.items,
                    boltcutters: action.IsPickedUp
                }
            }
        default:
            return state;
    }
}

Idealy I'd love it to look like this:

const inventoryReducer = (state = inventoryDefaultState, action) => {
    switch (action.type) {
        case 'PICK_UP_{ITEM-NAME}':
            return {
                ...state,
                items: {
                    ...state.items,
                    {ITEM-NAME}: action.IsPickedUp
                }
            }
        default:
            return state;
    }
}

How can I achieve something like that?

Upvotes: 1

Views: 42

Answers (1)

AranS
AranS

Reputation: 1891

There are many ways to improve reducers readability and efficiency. For your case I'll try to implement what you suggested.

First of all you can add the item name to the action payload:

action.payload.itemName = 'spoon';

Then in the reducer you can have one action that fits all items:

const inventoryRedcer = (state = inventoryDefaultState, action) => {
    switch (action.type) {
        case 'PICK_UP_ITEM':
            return {
                ...state,
                items: {
                    ...state.items,
                    [action.payload.itemName]: action.payload.IsPickedUp
                }
            }
        default:
            return state;
    }
}

In case your unfamiliar with the [action.payload.itemName] syntax, it is called a computed property name, where you add properties to object literals on the fly. More on this here.

Upvotes: 1

Related Questions