Home > Software engineering >  Sending request if property does not exist while destructuring JS object
Sending request if property does not exist while destructuring JS object

Time:09-30

I have object with property which should be destructred. But if it has false value I want to fetch it from backend.

const { property = await someMethodThatSendsRequest() } = myObject;

But this is not working. The question is - Is this even possible ?

CodePudding user response:

Just use a variable as a default value:

const defaultProperty = myObject.property || await someMethodSendsRequest();
const { property = defaultProperty } = myObject;

CodePudding user response:

In a matter of fact, yes. It is possible. However, your property needs to get accessed in order to get a result of someMethodThatSendsRequest() since default parameters are evaluated at call time. A simple Sandbox that proves it.

  • Related