0
votes

For a learning and test project, I'm trying to return immutable redux data from reducer because safe data for component. this is my reducer code :

function itemsReducer(state = [], action) {
    switch(action.type) {
        case 'ITEMS':
            return [...action.data]
        default:
            return state
    }
}

And this is my loop code :

<ul>
    {
        this.props.items.map((item) => (
            <li>{item.name.first} {item.name.last}</li>
        ))
    }
</ul>

now every things work right, but after change on props with this method :

change() {
    this.props.items[0] = 'empty'
}

and after loading again items I have this error :

TypeError: Cannot read property 'first' of undefined

Apparently the items did not copy with spread syntax in my reducer and all changes override on that. after executing the data load action at all the index #0 is 'empty'

Thank you

1
How about using Immutable JS?Oliver
How are you dispatching the action, and what is passed in action.data ? how is the data from the store passed to the component ? your problem can come from many places, please add more detailsjo_va
@Oliver I've mapped dispatch and action.data comes from my actionirbgls

1 Answers

4
votes

You shouldn't be mutating the props directly in component, instead dispatch an action that updates the result in reducer

change() {
    this.props.updateItem({first: 'empty'}, 0);
}

and action creator would be

const updateItem = (item, index) => {
   return {type: 'UPDATE_ITEM', item, index}
}

and reducer

function itemsReducer(state = [], action) {
    switch(action.type) {
        case 'ITEMS':
            return [...action.data]
        case 'UPDATE_ITEM': 
            return [...state.slice(0, action.index), {...state[index], ...action.item}, ...state.slice(index+1)];
        default:
            return state
    }
}