简体   繁体   English

按文档 ID 更新单个文档 - Firestore

[英]Update single document by document ID - Firestore

I'm trying to have a like and unlike feature, based on whether the status is "unliked" or "liked".我正在尝试根据状态是“不喜欢”还是“喜欢”来拥有喜欢和不喜欢的功能。 When a liked product is clicked, the status should get updated.单击喜欢的产品时,状态应该会更新。 I cannot seem to figure out how to pass the current document's ID to.doc!我似乎无法弄清楚如何将当前文档的 ID 传递给.doc!

The starting state:起始 state:

const [entities, setEntities] = useState([]);

This is my unlike function (the entity.id obviously gives me an error - undefined):这与 function 不同(entity.id 显然给了我一个错误 - 未定义):

const unlikeProduct = async () => {

    firestore()
      .collection('likes')
      .doc(entity.id)
      .update({
        status: "unliked",
      })
      .then(() => {
          console.log("unliked");
        Alert.alert(
          'You have unliked this product!',
        );
      });
  };

The button that sends a call to the unlike function:向不同的 function 发送呼叫的按钮:

<View style={styles.addToCartBtn}>
              <Icon name="heart" size={15} color={colours.white} onPress={() => unlikeProduct()}/>
            </View>

This function displays all the products which have status "liked":此 function 显示所有状态为“喜欢”的产品:

    firestore()
      .collection('likes')
      .where('status', '==', 'liked')
      .onSnapshot(
        (querySnapshot) => {
          const newEntities = [];
          querySnapshot.forEach((doc) => {
            const entity = doc.data();
            entity.id = doc.id;
            newEntities.push(entity);
          });
          setEntities(newEntities);
        },
        (error) => {
          console.log(error);
        },
      );
  }, []);

tldr; tldr; I just want to retrieve the document ID of the product I'm trying to unlike.我只是想检索我想要不像的产品的文档 ID。

Assuming you are mapping over the entities for displaying the Views, you can access each entity's id and pass it to your unlikeProduct function.假设您正在映射实体以显示视图,您可以访问每个实体的 id 并将其传递给您的 distinctProduct function。 Something like this:像这样的东西:

{entities.map((entity) => (
  <View style={styles.addToCartBtn}>
    <Icon name="heart" size={15} color={colours.white} onPress={() => unlikeProduct(entity.id)}/>
  </View>
))}

Then receive the entity.id in your unlikeProduct function as a parameter and it wont be undefined anymore.然后在您的 distinctProduct function 中接收 entity.id 作为参数,它将不再是未定义的。 Like so:像这样:

const unlikeProduct = async (id) => {

firestore()
  .collection('likes')
  .doc(id)
  .update({
    status: "unliked",
  })
  .then(() => {
      console.log("unliked");
    Alert.alert(
      'You have unliked this product!',
    );
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM