How to create new object as default arg object

48 Views Asked by At

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.

1

There are 1 best solutions below

3
junvar On BEST ANSWER

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