Home > database >  My firebase realtime push key is changed when I save it in array in react native
My firebase realtime push key is changed when I save it in array in react native

Time:02-23

I am saving order data in firebase realtime but the push key that I save in array object is different from what I get as push key

function confirmOrder() {
  let array = []
  const Oid = firebase.app().database(DATABASE_URL).ref('/Order/').push();

  array.push({
    total: getTotal(),
    oid: Oid.key,
    totalItems: cartItems.length
  })

  for (let index = 0; index < cartItems.length; index  ) {
    var key = `item${index   1}`;
    var obj = {};
    obj[key] = cartItems[index].qty   ' '   cartItems[index].name   ' Rs.'   cartItems[index].price;
    array.push(obj)
  }

  setOrder(Object.assign(...array))
  firebase.app().database(DATABASE_URL).ref('/Order/'   Oid.key).set(order);
}

enter image description here

CodePudding user response:

I'm not sure it's the cause of the issue, but can you try this (shorter) version of the last line?

Oid.set(order);

Update: the setState method and useState hooks asynchronously update the state, so order won't yet be updated on the next line.

You can either wait for the order to complete, or simply use array as the value:

Oid.set(Object.assign(...array));

Also see:

  • Related