I would like to show the user a list of items that they have recently viewed.
I would like to do this for users that have logged in and those who haven’t.
What is the best way of identifying a user that has not logged in?
I was thinking of just creating a cookie and having a collection called “cookies” with each document in the collection having an array called “recent documents”. Maybe I can periodically delete any documents which has an old cookie.
Is there a better way though? Is there a way I can use localStorage on the client’s browser but which doesn’t get lost if close the tab or even if they refresh the page?
You could set the session and create a document in the database related to that session value, however yes you would need to go through and delete old documents that haven’t been accessed in a while.
Exactly, definitely go with client-side storage (options being: html5 localstorage; plain old cookies; other, more obscure choices) if you don’t need the data on the server. Offloading what you can to the client is always a good idea when there’s no actual reason against that (which might be something like sensitiveness of data, necessary to have absolute reliability in persistence (which you don’t have with client-side storage since the user could at any point decide to clear all stored data)).
I know there’s several packages that use localstorage and fall back to cookies if the former is not available. Use one of those and you should be good.
Put this on the server only if you actually want to do something with the data on the server and/or need to be sure it won’t just be cleared without your consent. Otherwise… pure client-side.
Why not just do this to detect if the user is logged in?
if(Meteor.user()) {
//Show items
}
I usually add this whenever I have an action or thing that the user needs to be logged in for. Also, as I design tip why not show recently viewed for non-users too? It’s not like a thing that is user-dependent.
I have implemented something similar using persistent session.
I store recent searches here. If the user is logged in, that is stored and retrieved in the user’s document. Else, it pulls and pushes changes to the array in the session. You get to use the same syntax as the regular session. So far it has been working as promised
I did it the denormalized way and the normalized way and I prefer the
latter because it reduces the amount of rerendering. I would recommend
normalizing data when you can.
but yes, I stored the searches in an array field in meteor.users.profile.