Skip to content
Advertisement

How to push data as an array of an index to firebase?

I have an keys and want to push it to a specific item in my DB and i use .push() method when I add an item to firebase but it does not work as what I need it generates a new key and inside it add index

what i got

--Orders
  -LASDAWWDMASDsad
  -0:"orderOne"
  -DAWKDAWKWKDKADW
  -0:"OrderTwo"
  ...

What I need

--Orders
  -0:"orderOne"
  -1:"orderTwo"
  -2:"orderThree"
  ...

Code

const displayTable = document.getElementById('display-table')
  ,   lipProCkBxs  = document.querySelectorAll('#lip-pro input[type=checkbox]')
  ,   tableTotal   = document.querySelector('#display-table tfoot tr td:last-child')

const {snapshotVal, uid, serviceDB} = this.state;

onPress: () => {
            let arr = [snapshotVal];
            // console.log(arr); // ["orderOne"]
            database()
              .ref(`Providers/users/${uid}`)
              .child('rejectedOrders')
              .push(arr)
              .then(
                () => console.log('Done'),
                setTimeout(() => {
                  this.props.navigation.goBack();
                }, 200),
              )
              .catch(error => console.log('@error', error));
            }

SOLVED By JS :”D

i make a query to get the length of a rejectedOrders then when i want to updates i just increase the length +1 And it works well :3

componentDidMount() {
  let uid = auth().currentUser.uid;

  database()
    .ref(`Providers/users/${uid}`)
    .child('rejectedOrders')
    .on('value', snapshot =>
    this.setState({arrlength: snapshot.val().length - 1}),
    );
}

onPress: () => {
  let arr = [snapshotKey];
  console.log(arr);

  let updates = {};
  // updates[Math.floor(Math.random() * 10)] = snapshotKey;
  updates[arrlength + 1] = snapshotKey;
  database()
    .ref(`Providers/users/${uid}`)
    .child('rejectedOrders')
    // .push(...arr)
    .update(updates)
    .then(...)
}

Advertisement

Answer

You can use set() instead of push():

database()
              .ref(`Providers/users/${uid}`)
              .child('rejectedOrders')
              .set(arr)
              .then(
                () => console.log('Done'),
                setTimeout(() => {
                  this.props.navigation.goBack();
                }, 200),
              )
              .catch(error => console.log('@error', error));
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement