How to reload the model when using this.get('store').query? - javascript

I have a user model with attributes name and city, i am fetching 25 records at a time from server since there are lot of user records
so my routes has this
model(){
return this.get('store').query('user', {page:1}); }
which fetches me the first 25 records
Now in my template i have a button which on click hits the action to fetch the next 25 records ie
action:{
findMoreUsers(){
this.get('store').query('user', {page:2});
} }
Now in the browser, in the ember data the new records are loaded ie it shows 50 records
but when i try to do something like this.get('model'), it gives me the only the old records but not the newly loaded records
So how to to refersh the model so that it shows me all the old as well as new records(50 records)?
Thanks

This is because you haven't changed the model itself, which is just the result of a request to your server. I would recommend:
```
page: 0,
beforeModel() {
return this._findMoreUsers();
},
model() {
return this.get('store').findAll('users');
},
_findMoreUsers() {
this.get('store').query('user', { page: this.incrementProperty('page') });
}
```
Or something along those lines.
Then you can use this.store.peekAll('users') to retrieve all users that have been loaded into the store. If you need to change the model, you'll probably need to this.get('model').pushObjects(...).

Related

Vue3 refresh loses data

forEach() cannot get all element from an Proxy array?
I have a local database with 4 users. I use dynamic router [ http://localhost:8080/user/:id ] ,to get their id as a prop . and render a card with user datas.
every thing runs smoothly when I run locally. Then I add a register as a user function. I use fetch() to send data to "firebase" , and get data from "firebase" to render this card.
Now,I have 4 users' data are still in LOCAL,1 user's data is at SERVER. I want to render them together.I fetch the server side data ,and merge to local data array.
[mystery occurs here!]
I use unshift() method,so Local data have 5 users.
When I enter the page by '<router-link>' ,5 objects can be accessed. However, when I reload this page by [chrome browser refresh button] . Only 4 objects available.
I can see 5 objects in Proxy ,just cannot get it.Test the proxy length ,is 4.
methods: {
async loadTutors() {
//loading
await this.$store.dispatch["homepage/loadTutors"];
console.log("received");
//loading will unshift the data,getters can get it.
const tutors = await
this.$store.getters["homepage/tutor"];
console.log(tutors); //I can get 5 obj here
tutors.forEach((el) => console.log(el)); //only
get 4 obj here????
this.loading = false;
}
}
Question solved.Please look at the answer~
This problem emerge is because Vue3 will lost data storage in memory when refresh. We need to store it.
Add blow to [app.vue] ....
<script>
export default {
created(){
//when loading access to data which is stored in sessionStorage
if(sessionStorage.getItem('storeState')){
//replaceState
this.$store.replaceState(Object.assign({},this.$store.state,JSON.parse(sessionStorage.getItem('storeState'))))
}
//when refresh store vuex data to sessionStorage
window.addEventListener('beforeunload',()=>{
sessionStorage.setItem('storeState',JSON.stringify(this.$store.state))
})
}
}
</script>
TIPS:
this solution will have an impact on Vuex. cause the fail of data updated.Hope someone can improve this solution.
I now re-fetch the data when the needed data is not in Proxy.
3.
Also,there is an plugin in github : https://github.com/robinvdvleuten/vuex-persistedstate
(However ,it is deprecated. )

Is it a good approach to use firebase once method when retrieving all posts on ionViewWillEnter?

I am retrieving all posts (news) from firebase using the once method and showing it on the home tab (the first tab when the app is launched) :
get_all_posts(){
this.posts = [];
firebase.database().ref('/posts/').once('value').then(snapshot => {
.... //rest of the code
}
}
This will be fired in the ionViewWillEnter():
ionViewWillEnter(){
this.get_all_posts();
}
In this case, get_all_posts method will be fired everytime the "home" tab is pressed right? which will get all posts again from the DB or for the entire session (from opening the app till closing the app running on the phone)the news retrieved from the first time only will be displayed?
The news retrieved at first time with once() will fetch all the data from the reference you want to show, this will fetch the data just once and then detach the listener to the reference. When you press again your home button it will fetch again the data that belongs to that reference and will pull it from the database, if there is new content it will be displayed, if not, the first fetched data will be shown.
From your question
Is it a good approach to use firebase once method when retrieving all
posts on ionViewWillEnter?
Yes, in my opinion, it is a good practice to just ask for the data once and then display it to the user, because if you use on() you will be always listening for new data and your home screen might be updated with new content before the user can see the first fetched news.

MeteorJS - No user system, how to filter data at the client end?

The title might sound strange, but I have a website that will query some data in a Mongo collection. However, there is no user system (no logins, etc). Everyone is an anonymouse user.
The issue is that I need to query some data on the Mongo collection based on the input text boxes the user gives. Hence I cannot use this.userId to insert a row of specifications, and the server end reads this specifications, and sends the data to the client.
Hence:
// Code ran at the server
if (Meteor.isServer)
{
Meteor.publish("comments", function ()
{
return comments.find();
});
}
// Code ran at the client
if (Meteor.isClient)
{
Template.body.helpers
(
{
comments: function ()
{
return comments.find()
// Add code to try to parse out the data that we don't want here
}
}
);
}
It seems possible that at the user end I filter some data based on some user input. However, it seems that if I use return comments.find() the server will be sending a lot of data to the client, then the client would take the job of cleaning the data.
By a lot of data, there shouldn't be much (10,000 rows), but let's assume that there are a million rows, what should I do?
I'm very new to MeteorJS, just completed the tutorial, any advice is appreciated!
My advice is to read the docs, in particular the section on Publish and Subscribe.
By changing the signature of your publish function above to one that takes an argument, you can filter the collection on the server, and limiting the data transferred to what is required.
Meteor.publish("comments", function (postId)
{
return comments.find({post_id: postId});
});
Then on the client you will need a subscribe call that passes a value for the argument.
Meteor.subscribe("comments", postId)
Ensure you have removed the autopublish package, or it will ignore this filtering.

Mean js - display updates in real time

I'm new to meanjs, I just created a new module for adding products. These products are displayed in the home page. But the display in home page is not getting updated real time. I just added new product in one tab, and the products list in the other tab need to be refreshed to see the change. How can this be done at real time ?
Edit:
By updation I meant is, when ever a new record is been added to database, the product display should update in realtime. Now I need to refresh the page to see the newly added product.
My code is
Client
$http.get('/latestproducts').
success(function(data, status, headers, config) {
$scope.latestproducts = data;
})
Server
exports.getlatestProducts = function(req, res) {
Product.find().sort('-created').populate('user', 'displayName').exec(function(err, products) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(products);
}
});
If you mean browser tabs, mean.js won't do if fo you. You can use sockets to inform server that changes were made and then broadcast message to all active tabs to refresh data. You can also try window.blur/window.focus events to reload data.
If you have list of products and product form on the same page, you have 2 options:
add saved item to your local collection after you save poduct and recive success message from server.
Update local collection(get list of objects from the server) after you save poduct and recive success message from server.
I just released angular-socket-resource. Once you use a service instead of performing the http request manually, you can use that to automatically listen for socket.io updates that will update your local data.

Get same Item collection but with different limits

In my Backbone project, I am getting a collection of Items through the following Model:
MyApp.models.Items = Backbone.Model.extend({
url: "getItems"
});
and then later:
var model = new MyApp.models.Items();
model.fetch().then(function(data){
// do something here with fetched data
});
This Implementation works fine but I have a situation where I am getting all the Items on Home page and only 3 items in other page.
I feel it will be overkill if I fetch all the Items and then using the above model to limit it to 3 Items.
How can I use the same model to get a limited number of items or all items?
PS: I am new to Backbone.
The Backbone collection (Doc : http://backbonejs.org/#Collection) is a set of models.
Its best to use a backbone collection when you are dealing with data that is used to populate UI components like data gird / table, data lists e.t.c were you need a set of data.
MyApp.collections.ItemCollection = Backbone.Collection.extend({
model: Item,
url: "getItems"
});
The model attribute inside the collection specifies the type of data the is present in the collection. The collection uses this information to efficiently manage data inside it (merge during server fetch for already existing models /can pass raw json data to methods like add).
Using the collection fetch method(http://backbonejs.org/#Collection-fetch), data is fetched from the server.
var itemCollection = new MyApp.collections.ItemCollection();
itemCollection.fetch({
// The data property is used to send input data to the server method.
// Any data that will be required by the server method can be passed using this.
data: {
limit : 5
},
success : function(collection, response, options) {
//Do your logic
console.log("Success...");
}
error: function(collection, response, options) {
//Do your logic
}
});
In your scenario, you say you fetch all the items in homepage and only use part of it in other page.
For me, I would use router.
When the user moves from homepage to other page, you don't need to fetch new items, just choose the needed items (3 items) and render it.

Categories