javascriptnode.jsecmascript-2018

How to create new object as default arg object


So we may have this in a reducer:

const defaultState = {...};

export const userReducer = (state = defaultState, action: any) => {
   // ...
}

is there some way to get a defaultState object for each call to userReducer? Something like this:

const getDefaultState = () => ({...});

export const userReducer = (state = getDefaultState(), action: any) => {
   // ...
}

is this possible in JS? It might not be useful for a Redux reducer, but in general am curious.


Solution

  • Yes, as @blex, pointed out, your intentions are completely doable.

    Your snippet has a minor typo that may be causing you issues: parameters with default values (i.e. state) must be ordered after parameters with non-default values (i.e. action).

    Here's a minimalist example:

    let x = () => 3;
    let y = (a, b = x()) => a + b;
    
    console.log(y(5)); // 8
    console.log(y(5, 1)); // 6