how can i remove data in array from firebase by React native?

梦想的初衷 提交于 2020-07-09 11:46:29

问题


I'm making SNS app with React Native & Firebase.

I can create a comments in array of each Post, and show it as a Flatlist.

But I don't know how to remove each comment.

Please let me know where to check the document or link.

Or give me a hint. (In fact, it's been stuck here for almost two weeks.)

----action/post

export const getComments = (post) => {
  return (dispatch) => {
    dispatch({
      type: "GET_COMMENTS",
      payload: orderBy(post.comments, "date", "desc"),
    });
  };
};

export const addComment = (text, post) => {
  return (dispatch, getState) => {
    const { uid, photo, username } = getState().user;
    let comments = cloneDeep(getState().post.comments.reverse());
    try {
      const comment = {
        comment: text,
        commenterId: uid,
        commenterPhoto: photo || "",
        commenterName: username,
        date: new Date().getTime(),
        postTitle: post.postTitle,
        postDescription: post.postDescription,
        postUser: post.username,
      };
      console.log(comment);
      db.collection("posts")
        .doc(post.id)
        .update({
          comments: firebase.firestore.FieldValue.arrayUnion(comment),
        });
      comment.postId = post.id;
      comment.postTitle = post.postTitle;
      comment.postDescription = post.postDescription;
      comment.postUser = post.username;
      comment.uid = post.uid;
      comment.type = "COMMENT";
      comments.push(comment);
      dispatch({ type: "GET_COMMENTS", payload: comments.reverse() });

      db.collection("activity").doc().set(comment);
    } catch (e) {
      console.error(e);
    }
  };
};

----comment screen

import React from "react";
import styles from "../styles";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import {
  Text,
  View,
  TextInput,
  FlatList,
  KeyboardAvoidingView,
  TouchableOpacity,
  StatusBar,
  Animated,
  Dimensions,
} from "react-native";
import { addComment, getComments } from "../actions/post";
import moment from "moment";
import "moment/locale/ko";
moment.locale("ko");
import { Swipeable } from "react-native-gesture-handler";

class Comment extends React.Component {
  state = {
    comment: "",
  };

  componentDidMount = () => {
    const { params } = this.props.route;
    this.props.getComments(params);
  };

  postComment = () => {
    const { params } = this.props.route;
    this.props.addComment(this.state.comment, params);
    this.setState({ comment: "" });
  };

  rightActions = (dragX) => {
    const scale = dragX.interpolate({
      inputRange: [-100, 0],
      outputRange: [1, 0.9],
      extrapolate: "clamp",
    });
    const opacity = dragX.interpolate({
      inputRange: [-100, -20, 0],
      outputRange: [1, 0.9, 0],
      extrapolate: "clamp",
    });
    const deleteItem = async (id) => {
      await db.collection("posts").doc(id).delete();
      console.log("Deleted ", id);
    };

    return (
      <TouchableOpacity>
        <Animated.View style={[styles.deleteButton, { opacity: opacity }]}>
          <Animated.Text
            style={{
              color: "white",
              fontWeight: "800",
              transform: [{ scale }],
            }}
            onPress={() => deleteItem(item.id)}
          >
            !!!DELETE COMMENT!!!
          </Animated.Text>
        </Animated.View>
      </TouchableOpacity>
    );
  };

  render() {
    return (
      <View style={styles.container}>
        <StatusBar barStyle="dark-content" />
        <KeyboardAvoidingView
          enabled
          behavior="padding"
          style={[styles.container, styles.marginTop]}
        >
          <FlatList
            keyExtractor={(item) => JSON.stringify(item.date)}
            data={this.props.post.comments}
             renderItem={({ item }) => (
              <View>
                <Swipeable
                  renderRightActions={(_, dragX) => this.rightActions(dragX)}
                >
                  <View style={[styles.row, styles.space]}>
                    <View style={{ margin: 10 }}></View>
                    <View style={[styles.container, styles.left]}>
                      <Text style={styles.marginTop}>
                        <Text style={[styles.bold, styles.grayDark]}>
                          {item.commenterName}
                        </Text>

                        <Text style={styles.gray}>commented</Text>
                      </Text>
                      <Text style={[styles.gray, styles.marginTop5]}>
                        {item.comment}
                      </Text>
                      <Text
                        style={[styles.gray, styles.small, styles.marginTop]}
                      >
                        {moment(item.date).format("ll")}{" "}
                        {moment(item.date).fromNow()}
                      </Text>
                    </View>
                  </View>
                </Swipeable>
              </View>
            )}
          />
          <TextInput
            style={styles.input}
            onChangeText={(comment) => this.setState({ comment })}
            value={this.state.comment}
            returnKeyType="send"
            placeholder="leave comment"
            onSubmitEditing={this.postComment}
          />
        </KeyboardAvoidingView>
      </View>
    );
  }
}

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({ addComment, getComments }, dispatch);
};

const mapStateToProps = (state) => {
  return {
    user: state.user,
    post: state.post,
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Comment);


回答1:


For you to achieve data, you will need to read the data from your Firestore, modify the array data, removing the values that you want and then, save it back to your database - this can steps can be confirmed in this other post from the Community here.

In case you try this way, your code should be something like this one below.

const deleteComment = commentText => {
    const userPost = currentUser.Post

    // filter the Comment array
    const newComment = userPost.filter(
        comment => comment.text !== commentText
    )

    // update the doc with the filtered comment
    var userRef = db.collection('post').doc(user.uid)
    userRef.update({
        comment: newComment
    })

    // update my state to reload user data
    setCommentRemoved(true)

}

While this code is not tested, I believe it's a good starting point for your application. It removes the comment based in the user and the post where the comment is stored.

Besides that, you can try use the arrayRemove() function to perform this operation for you. The code for calling the function would be something like this.

docRef.update({
   comment: FieldValue.arrayRemove('idToRemove');
});

In addition, I would recommend you to get more information on how to manage and use arrays in Firestore, by checking this article from a Firestore developer here: Better Arrays in Cloud Firestore!

Let me know if the information helped you!



来源:https://stackoverflow.com/questions/62707675/how-can-i-remove-data-in-array-from-firebase-by-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!