0

Can someone help inspect my code here? I don't know where the syntax error is.
My eslint (atom editor) says:

Parsing error: Unexpected token, expected : (Fatal)

Here is the code:

const initialUserState = {}

const userReducer = (state = initialUserState, action: { type }) => {
  console.log(type)

  return state
}

I'm using babel-preset-env, which includes preset es2015, which then includes transform-es2015-destructuring.

And also, here is my babelrc config:

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "safari >= 7"],
        "uglify": true
      },
      "modules": false
    }],
    "react"
  ],
  "plugins": [
    "transform-object-rest-spread",
    "react-hot-loader/babel"
  ]
}

Thanks a lot.

Peter Wong
  • 86
  • 1
  • 4
  • That looks like typescript or something else with type annotations. It's invalid ES6 indeed. What did you expect it do, I cannot figure it out? What would the code look like without destructuring, or with destructuring in the function body? – Bergi Jun 01 '17 at 03:39

2 Answers2

0

You might be looking for

function userReducer(state = initialUserState, { action: type }) {
//                                             ^

which takes the action property of the second argument and introduces it as the variable type in the function scope. You just have misplaced the brace.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    My guess: `function userReducer(state = initialUserState, {type})` (`action` being the second argument passed in), or to actually be able to access `action`: `function userReducer(state = initialUserState, action) { const {type} = action; }`. – Felix Kling Jun 01 '17 at 03:45
  • @FelixKling As good as mine… We really need a clarification of the question. – Bergi Jun 01 '17 at 05:26
0

Thank you Bergi and Felix for answering my question and the useful ideas.


After some googling and trying, I found this code working.

const userReducer2 = (
  state = initialUserState,
  { type: { name, sex } = { name: 'Peter', sex: 'male' } }
) => {
  console.log(name, sex) // eslint-disable-line no-console

  return state
}

What I'm trying to do is define variable names and give them default values at the same time.

Though I still don't know how to give the second parameter an action name, this shoul be sufficient.

Peter Wong
  • 86
  • 1
  • 4
  • You might want to have a look at [this](https://stackoverflow.com/a/26578323/1048572). And no, there's no way to make a parameter named and have it destructured at the same time. Just move the destructuring inside the function body for that. – Bergi Jun 01 '17 at 05:32