Reputation: 155
So, I have a prop that will sometimes be null. I want to either get the value or return null.
I am currently doing this:
getOr(
null,
`shift.id`,
ownProps
);
I am getting the shifts.id from the props, however if there's no shift.id
I'll get an error back. How can I either return shift.id
or null
?
Upvotes: 2
Views: 6439
Reputation: 1672
The way _.getOr
works is that it provides a default value (the first argument) in the case that the value referenced by the path (the second argument) cannot be found in the object (the third argument). It's actually the same as _.get
but the argument order is flipped.
An example case is here:
let myObjects = [{
shift: {
id: 1,
example: "text1"
}
},
{
shift: {
id: 2,
example: "text3"
}
},
{
shift: {
example: "text2"
}
}
]
myObjects.forEach((object) => {
let result = _.getOr(null, "shift.id", object)
console.log(result);
})
<script src="https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)"></script>
The console output is:
1
2
null
From what you have described though it's not clear to me that is actually what you are trying to do. Remember, get/getOr will return what's referenced by the path (even if it's already null) unless it's not there (as in undefined
), at which point it will return the default value.
So in this case, where there is no shift.id
you are asking _.getOr
to return null. It sounds like you are then getting an error from GraphQL when you try to use it with a null value. This isn't a problem with lodash in this case, but a problem with your data / how you are using GraphQL.
If this isn't the right tool for the job then I can't suggest anything else without seeing more of your code/knowing more about the problem. I would suggest taking another look at your overall problem and then perhaps asking a different question if needs be.
Upvotes: 3
Reputation: 1162
I have tried your snippet with the sparse information you provided and that works as designed, as far as I understand this. See also my repl.it.
code
const _ = require('lodash/fp');
var ownProps = { shifts : { id: 'test' }};
console.log(_.getOr(
null,
`shifts.id`,
ownProps
));
ownProps = { shifts : { foo: 'test' }};
console.log(_.getOr(
null,
`shifts.id`,
ownProps
));
output
test
null
Upvotes: 1