Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return an array from a reducer?

Tags:

reactjs

redux

I have an array of items. When the items update I dispatch an UPDATED_LIST action and pass along the item with its updated data.

For example:

const initialState = {
    items: []
}

const reducer = items(state = initialState, action) {
    switch(action.type) {
        case 'UPDATED_ITEMS':
            return { ...state, ...action.payload }
        default:
            return state
    }
}

I dispatch like so:

store.dispatch({
    type: 'UPDATED_ITEMS',
    payload: [ { name: "bob"}, { name: "harry" } ]
})

And mapStateToProps:

const mapStateToProps = state => ({ items: state.items })

My problem is when I try to access items from within a component it's an object instead of an array. I have to do the following to get access to the array:

const mapStateToProps = state => ({ 
    items: Object.keys(state.offers).map((k) => state.items[k])
})

Is it possible to get the items as an array without having to convert them?

like image 910
BugHunterUK Avatar asked Apr 26 '26 16:04

BugHunterUK


1 Answers

In your reducer update it to where you set items with the action payload. You were previously using the spread operator on your action payload which converts all your array indexes into the state object as keys.

const reducer = items(state = initialState, action) {
    switch(action.type) {
        case 'UPDATED_ITEMS':
            return { ...state, items: [...action.payload] }
        default:
            return state
    }
}

If you don't want a nested state in your mapStateToProps you can do this where you make your initial state an array. Similar to the todo reducer shown here. https://redux.js.org/basics/example-todo-list#reducerstodos.js

const initialState = [];

const reducer = items(state = initialState, action) {
    switch(action.type) {
        case 'UPDATED_ITEMS':
            return [ ...action.payload ];
        default:
            return state
    }
}

const mapStateToProps = state => ({ 
  items: state.items
})
like image 152
Kenneth Truong Avatar answered Apr 29 '26 06:04

Kenneth Truong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!