Spread properties in Redux

I am trying to use the spread properties in my reducers, but it is coming back with an invalid syntax error. My build supports the use of the spread operator as I only get the error in my reducers.

auth_types.js

export const AUTH_USER = 'AUTH_USER'
export const UNAUTH_USER = 'UNAUTH_USER'

auth_actions.js

import { AUTH_USER, UNAUTH_USER } from './auth_types'



   export function signinUser({ email, password }) {
      return function(dispatch) {
        axios.post(`${ROOT_URL}/signin`, { email, password })
          .then(response => {
            dispatch({ type: AUTH_USER })

            browserHistory.push('/feature')
          })
      }
    }

reducer.js

import { AUTH_USER, UNAUTH_USER } from '../actions/auth_types'

export default function(state = {}, action) {
  switch(action.type) {
    case AUTH_USER:
      return { ...state, authenticated: true }
    case UNAUTH_USER:
      return { ...state, authenticated: false }
  }

  return state
}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

From the documentation:

Since the object spread syntax is still a Stage 2 proposal for ECMAScript you’ll need to use a transpiler such as Babel to use it in production. You can use your existing es2015 preset, install babel-plugin-transform-object-rest-spread and add it individually to the plugins array in your .babelrc.

{
  "presets": ["es2015"],
  "plugins": ["transform-object-rest-spread"]
}

Note that this is still an experimental language feature proposal so it may change in the future.

Solution 2

If you are using webpack, you can fix this by enabling stage-2 preset.

First install npm package:

npm install --save babel-preset-stage-2

Then add stage-2 to the presets array in webpack.config.js:

module: {
  loaders: [
    {
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      query: {
        presets:[ 'es2015', 'react', 'stage-2' ]
      }
    }
  ]
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply