Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Data in Firebase using React

I am updating an object in firebase using React js. I'm using this boilerplate as reference.

  updateBookList: (id, data) => {
    return firebaseDb.ref('NewBooks').child(id).update(data).then(() => {
      return {};
    }).catch(error => {
      return {
        errorCode: error.code,
        errorMessage: error.message
      }
    });
  },

The following updates the Books fine.

What I want to do is return the result instead of returning a blank {}. How can I return the result of what I updated?

This is how I fetch books:

  fetchBooks: () => {
    return new Promise((resolve, reject) => {
      const bookSub = firebaseDb.ref('NewBooks').on("value", books => {
        resolve(books.val());
      }, error => {
        reject(error);
      })
    })
  },
like image 951
lost9123193 Avatar asked Jan 26 '17 04:01

lost9123193


People also ask

Which method is used to update the Firebase data?

If we want to write to a specific child of a node without overwriting other child nodes, we use the updateChildren() method. When we call updateChildren(), we can update lower-level child values by specifying a path for the key.

How do I get data from Firebase in React?

Now we just need to initialize a Firebase app using the configuration details we got from Firebase. Once that is done, we will get a reference to the database service provided by Firebase for our app and export it: const app = initializeApp(firebaseConfig); const db = getDatabase(app); export { db };


1 Answers

If you want to return the value, you need to retrieve it. You can do that using once and the value event, which returns a promise that resolves to a Firebase snapshot:

updateBookList: (id, data) => {
  let ref = firebaseDb.ref('NewBooks');
  return ref
    .child(id)
    .update(data)
    .then(() => ref.once('value'))
    .then(snapshot => snapshot.val())
    .catch(error => ({
      errorCode: error.code,
      errorMessage: error.message
    }));
}

Also, you could simplify your fetchBooks by using once there, too:

fetchBooks: () => {
  return firebaseDb.ref('NewBooks')
    .once("value")
    .then(snapshot => snapshot.val());
}

once returns a promise, so you don't have to create your own and you won't have a dangling event listener. The call to on in your implementation of fetchBooks will see a listener added with each call and multiple calls to resolve will be attempted if the database changes.

like image 91
cartant Avatar answered Sep 29 '22 14:09

cartant