Is there any way to get always updated copy of one node to another node in firebase

Issue

I am performing add to cart feature in android and my idea to do that is if nodes are given like this

Nodes

Items:
   |
   |--item1Key--
               |
               |--price:10
   |
   |--itemkey2--
               |
               |--price:20



User:
|
|--inCartItems:
          |
          |--itemKey1
          |
          |--itemKey2


I am doing this storing only the keys of items added in cart to inCartItems,not the price because if somehow I will admin will change the price from Items node then it will not reflect to inCartItmes node when I will store the price too in inCartItems node.

Can anyone suggest me more better way to do that? All answers will be
appreciated.

Now in this case when we store only the keys of items then there generates the issue given in my previous problem

Previouse problem

Edit —

// Here I successfully got all the keys in lyKey
for(ItemsExploreModel favkeys : ltKey)
{
    // Toast.makeText(getContext(), favkeys.getKey(), Toast.LENGTH_SHORT).show();
    mDatabase.getReference().child(FirebaseVar.ALLITEMS).child(favkeys.getKey()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot2) {
            if (snapshot2.exists())
            {
                ItemsExploreModel adp = snapshot2.getValue(ItemsExploreModel.class);
                ItemsExploreModel adp2 = new ItemsExploreModel(snapshot2.getKey());


                list.add(adp);
                listKey.add(adp2);
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

Here I have done same thing with Adding into Favorite.

Solution

As per to my experience working with Firebase database, it is completely fine to make nested queries.

However Dharmaraj’s answer is also good (to use cloud function to update data at multiple places) but it make duplicate copies of same data and in some case cloud function failed to update the data, that time it’ll return wrong data.

The structure you have prepared is good. No need to duplicate the data (Single Source of Data). So on change in data, you don’t need to worry about the other places where those changes has to be performed.

However, you just need to make nested query on app side.
The nested query you are performing is wrong. You are adding ValueEventListener.

According to this doc, ValueEventListener adds continuous listener on that node of child. And as per your needs, you don’t need to continuously listen to the data changes while listing card items. So I would suggest you to use `OnCompleteListener (documentation) to read item data once only that will improve your app performance as well.

Answered By – DHAVAL A.

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *