Reputation: 2502
I'm doing a little store pattern as indicated in the docs.
Here is my store object:
import Vue from 'vue';
import _ from 'lodash';
class EmployeeService {
constructor() {
this.employees = null;
this.url = 'http://url';
}
all() {
if (this.employees === null) {
return Vue.http.get(this.url)
.then(response => (this.employees = response.data.data));
}
return new Promise(resolve => resolve(this.employees));
}
find(id) {
const employee = _.find(this.employees, { id });
if (_.isUndefined(employee)) {
return Vue.http.get(`${this.url}/${id}`)
.then(response => response.data);
}
return new Promise(resolve => resolve(employee));
}
}
export default new EmployeeService();
The problem is in the find(id)
method, whenever I use the lodash function _.find()
, it always returns undefined
, even when the object does exist. But when I use vanilla js, like this:
const employee = this.employees.flter(emp => emp.id == id)[0];
It has no problem finding the object.
I would like to know why this happens, and find if it's a bug or is an expected behaviour.
Upvotes: 1
Views: 1401
Reputation: 1777
There is no problem of Vue.js. But it's in your _.find
. As the lodash docs _find says:
Iterates over elements of collection, returning the first element predicate returns truthy for.
In your code _.find(this.employees, { id });
, { id }
doesn't return a truthy value. For the predicate parameter, you should use
function(o) {
return o.id == id;
}
Or shorthand: {'id': id}
.
Upvotes: 1