Home > Software design >  Firestore add data over an object within a document's data REACT.JS
Firestore add data over an object within a document's data REACT.JS

Time:09-23

I want to add some data on the bookChapters object, like a random id and inside of it the name of the chapters, I tried this but it doesn't work, after I add the previous data I also want to add a new object "takeAways", like the previous one, inside the random id object.

enter image description here

export const createNewChapter = (bookId, inputText) => {
  return async dispatch => {
    dispatch(createNewChapterStart());
    try {
firebase
        .firestore()
        .doc(`Users/${bookId}/bookChapters/${inputText}`)
        .onSnapshot(querySnapshot => {
          //There I want to add the chapters to the firestore database
        });
      dispatch(createNewChapterSuccess(inputText));
    } catch (error) {
      dispatch(createNewChapterFail(error));
      console.log(error);
    }
  };
};

enter image description here

CodePudding user response:

I wanna know how to do add from scratch the bookChapters object

The database screenshot shows that the bookChapters object is a map. So to add (populate) this object you need to generate a simple JavaScript object with some properties as “key: value” pairs.

Something along these lines, making the assumption the chapter titles are in an Array:

  function arrayToObject(arr) {
    var obj = {};
    for (var i = 0; i < arr.length;   i) {
      obj[i] = arr[i];
    }
    return obj;
  }

  const chapterList = ['Intro', 'Chapter 1', 'Chapter2', 'Conclusion'];
  const bookChaptersObj = arrayToObject(chapterList);

  firebase.firestore().doc(`Users/${bookId}`).update(bookChaptersObj);

Or, if the document does not already exist:

firebase.firestore().doc(`Users/${bookId}`).set(bookChaptersObj, {merge: true});
  • Related