0

Basically, I want to update the comments for a post when the user adds a new comment. However, when the "handleClick" function is called the component is not rerendered with the updated comments and I get the following error:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

I am very confused why this is and I have been looking everywhere for a solution. The complete code for the component:

import React, { useState, useRef } from 'react';
import { Typography, TextField, Button } from '@material-ui/core';
import { useDispatch, useSelector } from 'react-redux';

import useStyles from './styles';
import { commentPost } from '../../redux/reducers/posts';

const CommentSection = ({ post }) => {
    const classes = useStyles();
    const [comments, setComments] = useState(post?.comments);
    const [comment, setComment] = useState("");
    const user = JSON.parse(localStorage.getItem('profile'));
    const dispatch = useDispatch();

    const handleClick = async () => {
        const finalComment = `${user.result.name}: ${comment}`;
        const newComments = await dispatch(commentPost({ value: finalComment, id: post._id }));
        setComments(newComments?.payload?.comments);
        setComment('');
    };

    return (
        <div>
            <div className={classes.commentsOuterContainer}>
                <div className={classes.commentsInnerContainer}>
                    <Typography gutterBottom variant="h6">Comments</Typography>
                    {comments.map((c, i) => (
                        <Typography key={i} gutterBottom variant="subtitle1">
                            {c}
                        </Typography>
                    ))}
                </div>
                {user?.result?.name && (
                    <div style={{ width: '70%' }}>
                        <Typography gutterBottom variant="h6">Write a Comment</Typography>
                        <TextField fullWidth minRows={4} variant="outlined" label="Comment" multiline value={comment} onChange={(e) => setComment(e.target.value)} />
                        <Button style={{marginTop: '10px'}} fullWidth disabled={!comment} variant="contained" color="primary" onClick={handleClick}>
                            Comment
                        </Button>
                    </div>
                )}
            </div>
        </div>
    );
};

export default CommentSection;
dro
  • 3
  • 3
  • The error shows that the `CommentSection` component unmounts after `commentPost` completes. So, state setters in next lines `setComments` and `setComment` are called on unmounted component. It's better to look at parent hierarchy why this component is unmounted. – Vaibhav Nigam Jun 16 '22 at 10:00
  • @VaibhavNigam so then how would I wait for the component to mount then set the state. And why does the component unmount after dispatch? I’m assuming because dispatching rerenders the component maybe? – dro Jun 16 '22 at 10:21
  • After unmount/mount, the component's state will reset to default defined by lines: `const [comments, setComments] = useState(post?.comments); const [comment, setComment] = useState("");`. Like I said, answer lies in the parent hierarchy. It is possible that when you dispatch the action, redux store updates and one of the parent re-renders. This might be removing `CommentSection` component from DOM temporarily causing the unmount. – Vaibhav Nigam Jun 16 '22 at 11:35

0 Answers0