Home > Back-end >  I want to modify my data in firebase but I am passing the property to be updated as an argument pf a
I want to modify my data in firebase but I am passing the property to be updated as an argument pf a

Time:08-27

I want to modify my data in firebase but I am passing the property to be updated as an argument of a function, but it's not working. please take a look at the code to better understand what I am trying to say.

export const updateGameData = async (uid, level, playerStar, moves) => {
  const userDocRef = doc(db, "users", uid);
  const data = {
    levels: {
      level: { star: playerStar, playerMoves: moves },
    },
  };
  try {
    await setDoc(userDocRef, data, { merge: true });
  } catch (error) {
    console.log(error);
  }
};

As you can see I am passing level as an argument but it not taking the value of the level I passed as an argument when I use it as a property to create an Object. Please help me out.

CodePudding user response:

Your question isn't entirely clear, but I believe level is a variable that should hold the key to push to, and not a value.

In JS, creating an object works like this:

const obj = {
  level: 1
}

Will create an object with a single key a that has value 1.

What if we want a variable to hold the key to save to?

const level = 12

const obj = {
  level: 1
}

This doesn't change the output, because level is a literal string in this object definition. However if we wrap it in brackets like so: [level] inside the object definition...

const level = 12

const obj = {
  [level]: 1
}

We will have an object with a single key 12 that has value 1.

This is because brackets as the key name will cause the JS expression inside the brackets to be evaluated and the expression should return a result that can then be used as key.

See MDN computed property names for a more detailed explanation.

You want your data defined like this:

const data = {
    levels: {
      // notice brackets
      [level]: { star: playerStar, playerMoves: moves },
    },
  };
  • Related