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.
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
Use _.getOr(defaultValue, path, object)
from lodash/fp
.
Sources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With