1

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);

enter image description here

  • Does this answer your question? [How to delete object from array in firestore](https://stackoverflow.com/questions/52150386/how-to-delete-object-from-array-in-firestore) – Jeremy Jul 03 '20 at 05:25
  • @reactmania please, consider accepting my answer, in case it helped you. – gso_gabriel Jul 10 '20 at 06:34
  • @gso_gabriel i understood thanks for your answer but it's not working to me. i rebuilding logic again... – react mania Jul 12 '20 at 13:22

2 Answers2

0

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!

gso_gabriel
  • 4,199
  • 1
  • 10
  • 22
  • i think it is silly question but when i conduct as same as your advice, Can't find variable : currentUser. could you please let me know what value should be input instead of currentUser? – react mania Jul 03 '20 at 08:42
  • currentUser is the actual signed in user. in case you are using [Firebase auth (the recommended way for auth)](https://firebase.google.com/docs/auth/web/start) you can get it like in here https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user – Methkal Khalawi Jul 03 '20 at 09:09
0

Deleting whole flatlist in one go using firestore,

filter data = (_item) => {
    this.setState({ users: this.state.users.filter(item => item. Key=== _item)});
    console.log(this.state.favorites);
}

Call this function in button deleteAllData code given below,

<Touchable Opacity 
        onPress={() => {async function massDeleteUsers() {
            // Get all users
            const usersQuerySnapshot = await firestore().collection('user').get();             
            
            // Create a new batch instance
            const batch = firestore().batch();
            usersQuerySnapshot.forEach(documentSnapshot => { batch.delete(documentSnapshot.ref); });
            return batch.commit();
        }         
        massDeleteUsers().then(() =>{
         this.filterdata();
         console.log('All users deleted in a single batch operation.')})}
         }>
rcanpahali
  • 2,565
  • 2
  • 21
  • 37