I have a model with tasks, and i wantto get data filtered by status and show result in different lists.
so i have a construction with does't work as i want.
tasks: Ember.computed(function(){
var modelTasks = this.get('store').findAll('task');
return {
todo: modelTasks.filterBy('status', 'todo'),
inProgress: modelTasks.filterBy('status', 'inprogress'),
done: modelTasks.filterBy('status', 'done')
};
}),
I'm new, so please be tolerant.
Why do you need tasks computed property?.
findAll returns Promise so your code is not correct.
Async computed properties little tricky - read this ignite article for more info.
I would say, data fetching should happen at the route level, so corresponding route js file model hook you can write,
export default Ember.Route.extend({
model() {
return this.get('store').findAll('task').then((result) => {
return {
todo: result.filterBy('status', 'todo'),
inProgress: result.filterBy('status', 'inprogress'),
done: result.filterBy('status', 'done')
};
});
}
});
inside corresponding hbs file, you can access it like model.todo
Related
I am trying to implement a search function where a user can return other users by passing a username through a component. I followed the ember guides and have the following code to do so in my routes file:
import Ember from 'ember';
export default Ember.Route.extend({
flashMessages: Ember.inject.service(),
actions: {
searchAccount (params) {
// let accounts = this.get('store').peekAll('account');
// let account = accounts.filterBy('user_name', params.userName);
// console.log(account);
this.get('store').peekAll('account')
.then((accounts) => {
return accounts.filterBy('user_name', params.userName);
})
.then((account) => {
console.log(account);
this.get('flashMessages')
.success('account retrieved');
})
.catch(() => {
this.get('flashMessages')
.danger('There was a problem. Please try again.');
});
}
}
});
This code, however, throws me the following error:
"You cannot pass '[object Object]' as id to the store's find method"
I think that this implementation of the .find method is no longer valid, and I need to go about returning the object in a different manner. How would I go about doing this?
You can't do .then for filterBy.
You can't do .then for peekAll. because both will not return the Promise.
Calling asynchronous code and inside the searchAccount and returning the result doesn't make much sense here. since searchAccount will return quickly before completion of async code.
this.get('store').findAll('account',{reload:true}).then((accounts) =>{
if(accounts.findBy('user_name', params.userName)){
// show exists message
} else {
//show does not exist message
}
});
the above code will contact the server, and get all the result and then do findBy for the filtering. so filtering is done in client side. instead of this you can do query,
this.store.query('account', { filter: { user_name: params.userName } }).then(accounts =>{
//you can check with length accounts.length>0
//or you accounts.get('firstObject').get('user_name') === params.userName
//show success message appropriately.
});
DS.Store#find is not a valid method in modern versions of Ember Data. If the users are already in the store, you can peek and filter them:
this.store.peekAll('account').filterBy('user_name', params.userName);
Otherwise, you'll need to use the same approach you used in your earlier question, and query them (assuming your backend supports filtering):
this.store.query('account', { filter: { user_name: params.userName } });
I'm somewhat new to React, and using the re-base library to work with Firebase.
I'm currently trying to render a table, but because of the way my data is structured in firebase, I need to get a list of keys from two locations- the first one being a list of user keys that are a member of a team, and the second being the full user information.
The team node is structured like this: /teams/team_id/userkeys, and the user info is stored like this: /Users/userkey/{email, name, etc.}
My table consists of two react components: a table component and a row component.
My table component has props teamid passed to it, and I'm using re-base's bindToState functionality to get the associated user keys in componentWillMount(). Then, I use bindToState again to get the full user node, like so:
componentWillMount() {
this.ref = base.bindToState(`/teams/${this.props.data}/members`, {
context: this,
state: 'members',
asArray: true,
then() {
this.secondref = base.bindToState('/Users', {
context: this,
state: 'users',
asArray: true,
then() {
let membersKeys = this.state.members.map(function(item) {
return item.key;
});
let usersKeys = this.state.members.map(function(item) {
return item.key;
});
let onlyCorrectMembersKeys = intersection(membersKeys, usersKeys);
this.setState({
loading: false
});
}
});
}
});
}
As you can see, I create membersKeys and usersKeys and then use underscore.js's intersection function to get all the member keys that are in my users node (note: I do this because there are some cases where a user will be a member of a team, but not be under /Users).
The part I'm struggling with is adding an additional rebase call to create the full members array (ie. the user data from /Users for the keys in onlyCorrectMembersKeys.
Edit: I've tried
let allKeys = [];
onlyCorrectMembersKeys.forEach(function(element) {
base.fetch(`/Users/${element}`, {
asArray: true,
then(data) {
allKeys.prototype.concat(data);
}
});
});
But I'm receiving the error Error: REBASE: The options argument must contain a context property of type object. Instead, got undefined
I'm assuming that's because onlyCorrectMembersKeys hasn't been fully computed yet, but I'm struggling with how to figure out the best way to solve this..
For anyone dealing with this issue as well, I seemed to have found (somewhat) of a solution:
onlyCorrectMembersKeys.map(function(item) {
base.fetch(`/Users/${item}`, {
context: this,
asObject: true,
then(data) {
if (data) {
allKeyss.push({item,data});
this.setState({allKeys: allKeyss});
}
this.setState({loading: false});
},
onFailure(err) {
console.log(err);
this.setState({loading: false});
}
})
}, this);
}
This works fine, but when users and members state is updated, it doesn't update the allkeys state. I'm sure this is just due to my level of react knowledge, so when I figure that out I'll post the solution.
Edit: using listenTo instead of bindToState is the correct approach as bindToState's callback is only fired once.
I am trying to do the following when visiting reviews/show (/reviews/:id):
Load two models from the server: One review and one user.
I only have access to the review's id, so I need to load it first, to get the userId
And then, when that has finished loading and I now have the userId, query the user using the userId attribute from the review
Finally, return both of these in a hash so I can use them both in the template
So two synchronous database queries, and then return them both at once in the model hook of the route.
I don't mind if it's slow, it's fast enough for now and I need it to work now.
This is what I've tried and it doesn't work:
reviews/show.js
export default Ember.Route.extend({
model: function(params) {
var user;
var review = this.store.findRecord('review', params.id).then(
function(result) {
user = this.store.findRecord('user', result.get('userId'));
}
);
return Ember.RSVP.hash({
review: review,
user: user
});
}
});
You can do this:
export default Ember.Route.extend({
model: function(params) {
var reviewPromise = this.store.findRecord('review', params.id);
return Ember.RSVP.hash({
review: reviewPromise,
user: reviewPromise.then(review => {
return this.store.findRecord('user', review.get('userId'));
})
});
}
});
The reason why user is undefined is because it hasn't been assigned in your first promise until the review is resolved, but Ember.RSVP.hash has received user as undefined.
I have a model, let's call it Task, that has a property assignee. I have another model Admin, that's a set of admins. On task, I want to add a property, admin, that looks up the assignee from the admins by email and returns that admin.
The primary key on Admin is not email, and in Ember Model, it doesn't look like it's possible to create a belongsTo association on any key other than the primary key. The reason I send over email rather than an id is that the admin doesn't always exist.
The Task model looks something like this:
import Em from 'ember';
import Admin from 'project/models/admin';
import PromiseObject from 'project/lib/promise-object';
var Task = Em.Model.extend({
id: Em.attr(),
name: Em.attr(),
assignee: Em.attr(),
admin: function() {
return PromiseObject.create({
promise: Admin.fetch({ email: this.get('assignee') })
}).then(function(json) {
return Admin.create(json);
}, function() {
return null;
});
}.property('assignee'),
adminName: Em.computed.oneWay('admin.name')
});
export default Task;
PromiseObject is just extending the PromiseProxyMixin, and looks like this:
import Em from 'ember';
export default Em.ObjectProxy.extend(Em.PromiseProxyMixin);
When I try to access the property, I can see the network requests for the admins going across the wire, and I can see the successful response with the correct details included. However, null is returned for the promise.
I'm looking to include {{task.adminName}} in my templates. I'm a little stumped at this point on the best way of resolving the admin promise correctly in my model.
You aren't returning the PromiseObject, you're returning a chained promise. You should just return the PromiseObject.
admin: function() {
var promise = $.getJSON("/admin").then(function(json) {
return Admin.create(json);
}, function() {
return null;
});
return PromiseObject.create({
promise: promise
});
}.property('assignee'),
Example: http://emberjs.jsbin.com/nobima/12/edit
Using Ember Model fetch with an object returns a collection, not a model (unless of course you're fetch isn't Ember Model). So json isn't what's being returned at that point. You probably want to do something along these lines.
admin: function() {
var promise = Admin.fetch({ email: this.get('assignee') }).then(function(collection){
return collection.get('firstObject');
}, function() {
return null;
});
return PromiseObject.create({
promise: promise
});
}.property('assignee'),
I have implemented find() and findAll() methods on my Property model. Both methods make asynchronous calls to an API. findAll() is called while connecting the outlets for my home route, and works fine. find() is called by Ember.js while connecting the outlets for my property route. Note that find() is not called when navigating to a property route through actions, but is called when you go directly to the route through the URL.
Here is my router:
App.Router = Ember.Router.extend({
root: Ember.Route.extend({
showProperty: Ember.Route.transitionTo('property'),
home: Ember.Route.extend({
route: '/',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet('home', App.Property.findAll());
}
}),
property: Ember.Route.extend({
route: '/property/:property_id',
connectOutlets: function(router, property) {
router.get('applicationController').connectOutlet('property', property);
}
}),
})
});
And here are my findAll() and find() methods:
App.Property.reopenClass({
find: function(id) {
var property = {};
$.getJSON('/api/v1/property/' + id, function(data) {
property = App.Property.create(data.property);
});
return property;
},
findAll: function() {
var properties = [];
$.getJSON('/api/v1/properties', function(data) {
data.properties.forEach(function(item) {
properties.pushObject(App.Property.create(item));
});
});
return properties;
}
});
When I go to a route other than index, for example http://app.tld/#/property/1, the route gets rewritten to http://app.tld/#/property/undefined. Nothing is being passed to the content property of the Property controller. How can I make asynchronous calls in the find() method? Unless I am mistaken, asynchronous calls work fine in the findAll() method, which is the source of my confusion.
This question is similar to Deserialize with an async callback, but I'm using the find() method instead of overriding the deserialize() method.
Thanks in advance.
I found that setting the id property explicitly solves this problem. In your case this would look like this.
find: function(id) {
var user = App.User.create();
$.getJSON('/api/v1/property/' + id, function(data) {
user.setProperties(data.user)
});
user.set("id",id); // <-- THIS
return user;
}
Once your user gets its properties set the view updates as normal. Ember just need the id part before in order to update the URL.
Hope this helps :-)
Here's what you want to be doing. I changed the model to User to make things a little clearer.
In the case of find(), you return a blank model instance that gets it's properties filled in when the AJAX request comes back. The nice thing about Ember's data-binding is that you can display this model in a view immediately and the view will update when the AJAX request returns and updates the model instance.
In the case of findAll(), you return a blank array that gets filled in when the AJAX request comes back. In the same way as find(), you can display this list of models (which at first will be blank) in a view and when the AJAX request returns and fills in the array, the view will update.
App.User.reopenClass({
find: function(id) {
var user = App.User.create();
$.getJSON('/api/v1/property/' + id, function(data) {
user.setProperties(data.user)
});
return user;
},
findAll: function() {
var userList = [];
$.getJSON('/api/v1/properties', function(data) {
var users = data.users.map(function(userData) {
return App.User.create(userData);
});
userList.pushObjects(users);
});
return userList;
}
});