Reputation: 3511
I'd like to use destructuring right inside a constructor call like this:
signup: async (userInfo) => {
const user = new User({ email, password, privacyPolicyConsent, username } = userInfo);
}
But params are undefined.
I want to prevent from injection of undesirable params by redeclaration, therefore I don't want to pass whole object like this:
signup: async (userInfo) => {
const user = new User(userInfo);
}
For now my working solution is as follow:
signup: async (userInfo) => {
const { email, password, privacyPolicyConsent, username } = userInfo;
const user = new User({ email, password, privacyPolicyConsent, username });
}
But I got a feeling I could write this part in a better way. Did I miss something? Any advice regarding best practices appreciated.
Upvotes: 1
Views: 155
Reputation: 2668
You can Destruct it directly, like the following
signup: async ({ email, password, privacyPolicyConsent, username }) => {
const user = new User(email,password,privacyPolicyConsent,userName);
}
signUp(userInfo);
UPDATE
This will prevent to handle destruct error if it is sent undefined so you need to check for userInfo before you send it
if(userInfo) signUp(userInfo);
UPDATE 2
if you dont want to check for userInfo if it is undefined you can assign a default value in method level like following
signup: async ({ email, password, privacyPolicyConsent, username }={}) => {
const user = new User(email,password,privacyPolicyConsent,userName);
}
Upvotes: 4
Reputation: 1315
Ooh so would I.
This is what I tend to do (an immediately invoked function):
signup: async userInfo => {
const user = new User((({ email, password, privacyPolicyConsent, username }) =>
({ email, password, privacyPolicyConsent, username })
))(userInfo));
}
It reduces it to one statement, but doesn't remove the problem of duplicated (and ugly) code.
Maybe a function to do it might be best practices:
const dstr = (obj, ...keys) => keys.reduce((o, k) => { o[k] = obj[k]; return o; }, {});
// ...
const user = dstr(userInfo, email, password, privacyPolicyConsent, username);
Or you could use that reduce method to create it inline :)
Intrigued what alternatives there are.
(EDIT) The above is assuming that you can't destructure the object beforehand.
Upvotes: 0