0

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
mayra
  • 73
  • 8

1 Answers1

0

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807