maximus26
maximus26

Reputation: 65

Redux add object to array

I have the following problem...

I want to add an object to an array of objects using redux in my react-native application. I get this error message:

Invalid attempt to spread non-iterable instance


// my action

export function newTaskAction(){
  return{
    type: ADD_NEW_TASK,
    payload: {
      new: { id: '5', task:'test123'}
    }
  }
}



//my reducer

export default function taskReducer(state = initialUserState, action){
    switch (action.type)
    {
        case ADD_NEW_TASK :
            return {
                ...state,
                tasks: [...state.tasks, payload.new]
            }
        default:
            return state
    }




const store = createStore(allReducers, {
 tasks: [
   {id: "1", task: "React Native lernen"},
   {id: "2", task: "Redux lernen"},
   {id: "3", task: "Etwas lesen"},
   {id: "4", task: "Einkaufen gehen"}
 ],
 user: 'Frank'
});

Upvotes: 2

Views: 8175

Answers (4)

mycroft16
mycroft16

Reputation: 825

In your initial state, if you have defined tasks: null, then when you try to do a spread operator on [ ...state.tasks ] it will throw an error because it is null. Instead define tasks: []. You didn't post that as part of your code examples, so only guessing based on when I've had that same error.

Upvotes: 0

HABEEB RAHMAN PT
HABEEB RAHMAN PT

Reputation: 46

Please use Object.assign

 case Actions.CART_ADD_ITEM: 
        return Object.assign({}, state, { tasks: [...state.tasks,  { id: '5', task:'test123'}] });

Please use the task list in View like this

const mapStateToProps = (state) => ({
tasksList: state.tasksReducer.tasks} 
);


<FlatList
    data={this.props.tasksList}/>

Upvotes: 0

Siavash Rostami
Siavash Rostami

Reputation: 1933

Isn't it supposed to be?

return { ...state, tasks: [...state.tasks, action.payload.new] }

missing action

Upvotes: 0

N Fard
N Fard

Reputation: 1099

Change this line

[...state.tasks, payload.new] 

to

tasks: [...state.tasks, action.payload.new]

Upvotes: 2

Related Questions