Save favorites items for users in Firebase


#1

Hello,

Another thing I am trying to achieve is to give the user the possibility to save some favorite items from the collection so these favorites are shown in the first screen after login.

I have created a collection in Firebase named “users” and I have created users with the UID from the authentication section. The items to be saved as favorites are placed in a different collection and I am not sure how to create that connection. I thought about creating an icon in the UI that has 2 states depending if it is true or false the fact that it is favorite.

Also I believe that within each item in the collection there has to be a collection with all UID from each user so it says that particular item is favorite or not. But I don’t know exactly how to proceed with that link or reference and how to make it in React Studio.

Thank you.


#2

I think this has many different approaches. Check e.g. this video series about Firestore and storing “favorites”: https://www.youtube.com/watch?v=rffbpMzLrZ0

The simplest solution is of course to create userFavorites collection and store all favorite documents there and query the collection with a user id. This means that document data is duplicated into userFavorites collection when user presses “Favorite”.


#3

I understand the process but there is something I don’t get to comprehend completely. I have a collection of items and each of those items has different values/fields, something like:

/collectionItems {
     Item1 {
            name: Lorem
            image: ipsum 
            link: dolor
     }
     Item 2 {
            name: Lorem
            image: ipsum 
            link: dolor
     }
}

I also have a collection with the users information like uid, email, picture, etc. I understand I have to create another collection for the favorites. Inside this collection is where I don’t know exactly how to make it work. I am guessing each document has to be the uid for each user? How do I specify exactly that the user has Item1 in his favorites?


#4

I’m not quite sure what you mean by “I am guessing each document has to be the uid for each user? How do I specify exactly that the user has Item1 in his favorites?”…

In databases (SQL or noSQL) you always have to have some kind of unique identifier (or nested structure) to be able find the data you need. In this case every favorite document in Favorites collection needs to contain User Id which can be then used for retrieving favorites for certain user.


#5

Thank you so much for your answer.

Ok. I understand now that just specifying the ID of the items saved in favourites is enough to create the reference to the document. I thought it would be necessary to create some kind of reference to retrieve all the fields within that document saved in favorites.

I am going to try to do it with one and see if it works. Thank you!