0

I am working on a React Native project with Nested comment section. Comments are fetched as JASON data and rendered through a FlatList.

export default App = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  const getQuestions = async () => {
    try {
      const response = await fetch('https://..../api/q/289');
      const json = await response.json();
      setData(json);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getQuestions();
  }, []);


  const addCommentReply = () => {
    var newData = [
      {
        "qid": "540",
        "aid": "540",
        "content": "New Comment/Reply",
        "privacy": "true",
        "uid": "23",
        "name": "Jhone",
      },
    ];
    setData(data.concat(newData));
  }


  return (
    <Screen>
        <FlatList
          data={data}
          keyExtractor={({ qid }, index) => qid}
          renderItem={({ item }) => (
            <AppCommentReply content={item.content} uname={item.name} />
          )}
        />
      <CommentBox>
        <Button title="Add element" onPress={addCommentReply} />
      </CommentBox>
    </Screen>
  );
};
  1. Is FlatList a correct approach for a nested comment section?
  2. With {addCommentReply} i can add a comments to the main array stream. but when someone is replying to a comment, to render replies, I'm thinking of pushing that data just below the corresponding "qid" in the array. How to push data into the middle of the array?

1 Answer 1

1

The spread operator is helpful to insert an element into array:

function insert(arr, index, item) {
  return [
      ...arr.slice(0, index),
      item,
      ...arr.slice(index)
 ];
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.