Home > Software engineering >  How to update a dynamic field name in Firebase Firestore?
How to update a dynamic field name in Firebase Firestore?

Time:01-18

I want to do something like the below code in React Native:

await firestore()
      .collection('Users')
      .doc('ABC')
      .update({
        this.state.documentName: url,
      });

But I need this.state.documentName to be dynamic but VSCode is reporting an error saying ':' expected.. What am I missing?

Image of TypeScript annotation

CodePudding user response:

You were very close, in order to compute the field name, wrap it in square brackets:

await firestore()
      .collection('Users')
      .doc('ABC')
      .update({
        [this.state.documentName]: url,
      });

The update() method also accepts arguments in key-value pairs:

await firestore()
      .collection('Users')
      .doc('ABC')
      .update(this.state.documentName, url);

Note: You should make sure to employ appropriate security rules to prevent a user from promoting themselves to an admin if that information is also contained in their user document.

CodePudding user response:

Define the documentName from state outside of the async function in a variable then use it to update in the function

var db = firebase.firestore();
var documentName = this.state.documentName;
await db.collection("Users")
.doc('ABC')
.update({documentName: "bar"});
  •  Tags:  
  • Related