2

I am using React with react-redux and redux-actions.

I have the following reducer that keeps telling me

unexpected token, expected ","

but I am not sure why.

comments.js (reducer):

import { handleActions } from "redux-actions";
import {
  GET_COMMENTS,
  SET_COMMENTS,
  ADD_COMMENT
} from "../constants/actionTypes";

export default handleActions(
  {
    [GET_COMMENTS]: (state, action) => state,
    [ADD_COMMENT]: (state, action) => {
      const comments = {
        ...state.comments,
        action.payload
      };
      return {
        ...state,
        comments
      };
    },
    [SET_COMMENTS]: (state, action) =>
      Boolean(action.payload) ? action.payload : state
  },
  {}
);

The action causing trouble is ADD_COMMENT. I have tried it the following ways:

[ADD_COMMENT]: (state, action) => {
  ...state,
  comments: {
    ...state,
    action.payload
  }
}

or

[ADD_COMMENT]: (state, action) => ({
      ...state,
      comments: {
        ...state,
        action.payload
      }
})

as well as:

[ADD_COMMENT]: (state, action) => {
  return {
      ...state,
      comments: {
        ...state,
        action.payload
      }
  }
}

I am unable to see why my code is not correct, my linter in atom is saying its the dot between action and payload but I'm not sure.

The action creator just returns a type of ADD_COMMENT and payload of the individual comment in the following format:

{
    "id": 3,
    "parent": 1,
    "author": "admin",
    "author_is_staff": true,
    "content": "This is a test comment using the API rather than the Admin page, with author specified, with view changed"
}
You Nguyen
  • 9,961
  • 4
  • 26
  • 52
CHBresser
  • 185
  • 2
  • 2
  • 15

1 Answers1

6

You're trying to include a variable in an object without a key:

// This is fine
const comments = {
  ...state.comments
}

// This is not
const comments = {
  actions.payload
}

// Possible alternative:
const comments = {
  ...state.comments,
  payload: actions.payload
}

// Or if you want to destructure `actions.payload`:
const comments = {
  ...state.comments,
  ...actions.payload
}
coreyward
  • 77,547
  • 20
  • 137
  • 166
  • Ah. I'm in class right now but when I get out I will try it. I definitely think you are right, now that I hear it, it makes so much sense. state.comments is an object of objects, so I believe I have to destructure actions.payload into the comments. Will verify and get back to you. – CHBresser Oct 01 '18 at 23:27
  • You were correct. I was able to solve the issue, by first normalizing the data and then destructuring actions.payload into the new comments state. – CHBresser Oct 02 '18 at 02:51