cdmt
cdmt

Reputation: 913

React Redux - action failing, parsing error

I'm trying to learn react redux and I'm trying to create a simple example using a shopping list with get, delete and add items.

I have an example here that shows it working with get and delete items.

My problem is in the reducer with the add item.

Here is the same example but with the additem in reducer.

case ADD_ITEM:
  return{
    ...state,
    items: [...state.items, {id: uuid(),  action.payload}]
  } 

It's complaining about action.payload

The error I get locally is

./src/reducers/itemReducer.js
  Line 26:  Parsing error: Unexpected token, expected ","

  24 |       return{
  25 |         ...state,
> 26 |         items: [...state.items, {id: uuid(),  action.payload}]
     |                                                     ^
  27 |       }  
  28 |     default:
  29 |       return state  

Can anyone see what I'm doing wrong.

Upvotes: 1

Views: 336

Answers (2)

ApplePearPerson
ApplePearPerson

Reputation: 4439

You are creating an object with this statement {id: uuid(), action.payload}. You provide a key for the first entry but not one for the second. Looking at your items object it is expecting the name key.

Try changing it to this: {id: uuid(), name: action.payload}

Upvotes: 2

Vu Luu
Vu Luu

Reputation: 790

Edit your action:

export const addItem = (name) =>{
  return{
    type: ADD_ITEM,
    payload: { name }
  }
}

then, edit your reducer:

export default function(state = initialState, action){
  switch(action.type){
    case GET_ITEMS:
      return{
        ...state
      }
    case DELETE_ITEM:
      return{
        ...state,
        items: state.items.filter(item => item.id !== action.payload)
      }  
    case ADD_ITEM:
      return{
        ...state,
        items: [...state.items, {...action.payload, id: uuid()}]
      }  
    default:
      return state  
  }
}

Upvotes: 0

Related Questions