Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I invoke lodash/fp get and use a default value?

I'm using lodash/fp with react and am new to react. The documentation for _.get() says you can pass a default value:

If the resolved value is undefined, the defaultValue is used in its place.

But, in the signature does not show a defaultValue and passing it as third argument does not work, it is ignored:

import _ from "lodash/fp"

console.log("first:", _.get("email", profile.profile, "test"))
console.log("second:", _.get("email", profile.profile) ? _.get("email", profile.profile) : "test")
console.log("third:", profile.profile.email)

I get in the console:

app.js:251 first: undefined
app.js:252 second: test
app.js:253 Uncaught TypeError: Cannot read property 'email' of undefined

Since it is undefined as seen with error in "third" log, why doesn't the first give me empty string instead of undefined?

See related discussion.

How do I invoke lodash fp and have a default value used? Is this what getOr is for? I tried getOr and am not getting default value.

like image 545
WilliamKF Avatar asked Mar 30 '18 18:03

WilliamKF


2 Answers

In the docs you linked to, as you can see, the first argument to _.get is the object itself, not a string. If your primary object is profile, then that should be the first argument, and the second argument should be a string of the path you want.

_.get(profile, 'profile.email') refers to profile.profile.email

In /fp, _.get from lodash/fp doesn’t use defaultValue, and the solution is to use getOr, which works fine for me:

https://codesandbox.io/s/vp2opyjkl

like image 57
CertainPerformance Avatar answered Nov 20 '22 06:11

CertainPerformance


Use _.getOr(defaultValue, path, object) from lodash/fp.

Sources:

  • https://lodash.com/docs/4.17.11#get
  • https://github.com/lodash/lodash/wiki/FP-Guide
like image 25
Gunar Gessner Avatar answered Nov 20 '22 04:11

Gunar Gessner