Search code examples
reactjsecmascript-6reduxredux-actions

How do I allow for multiple statements in my reducer?


I am forced to use the redux-actions. In my reducer this code works:

return handleActions({
  [FOOBAR]: (state) => ({
    ...state, value: 'the user clicked something 2'
  })
}, {})

However, in the reducer I would like to console.log some stuff. How do I do this?


Solution

  • Your code currently returns an object from an arrow function to indicate the subsequent state. Instead of using shorthand arrow function syntax to implicitly return the object, you can use a block to house multiple statements including your console.log, not just an implicit return:

    [FOOBAR]: (state) => {
      console.log('Inside FOOBAR action')
      return {
        ...state, value: 'the user clicked something 2'
      }
    }
    

    The {} symbolize a block instead of an object literal because of the missing ()1. Thus, you can use other statements inside the block, but you must return your subsequent state object because it does not implicitly return.


    The reason why {} is a block and not an object literal here is because arrow functions have multiple acceptable syntaxes, one using a block:

    (param1, param2, …, paramN) => { statements }
    

    The JavaScript engine interprets the {} as a block. So, your code has ({}) which does mean an object literal because the parentheses can only be wrapped around an expression. Since a block is not an expression, and the object literal is an expression, the engine interprets it as an object literal.