Inline value destructuring #519
-
Hey folks 👋 I'm new to this library and I was wondering how one would destructure a Result's value inline: //...
const { isErr, value: user } = await register({ email, password})
if (isErr) {
return json({ fields, fieldErrors: { email: `That email address already exists` } })
}
// Everything went ok, create session and redirect user to profile page
return setUserInSession(user, '/profile') The /** Create new user with email and password */
export const createUser = async ({ email, passwordHash }: { email: string; passwordHash: string }): Promise<Result<SessionUserWithoutPassword, string>> => {
try {
return ok(
await db.user.create({...})
)
} catch (e) {
return err('Email already exists')
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hi @andrecasal – just had time to work through notifications and saw this! You can't destructure exactly like you have there because the //...
let result = await register({ email, password});
return result.match({
Ok: (user) => setUserInSession(user, '/profile'),
Err: (_) => json({ fields, fieldErrors: { email: `That email address already exists` } }),
}); |
Beta Was this translation helpful? Give feedback.
Hi @andrecasal – just had time to work through notifications and saw this! You can't destructure exactly like you have there because the
value
field is only available when you've verified that it's anOk
you're dealing with. This kind of scenario is in fact exactly what the.match()
method is for, though! Usingmatch
, you can get similarly nice-to-work-with code by doing something like this: