skip to Main Content

State isn’t updating. I am trying to create the edit function to make edits on posted comments. When the submit button is clicked, nothing changes on the front end. After I refresh the page the changes appear. I can’t seem to find where the problem is.

Content.js

// handle edit comments
    const editChat = (newComment) => {
        const updatedChatList = chats.map(chat => {
            if (topic.id === newComment.id) {
                return newComment
            } else {
                return chat;
            }
        });
        setChats(updatedChatList);
    }

ChatCard.js

function ChatCard({ chat, topic, deleteComment, editChat }) {
    const { user } = useContext(UserContext);
    const { id } = chat;
    const [editMode, setEditMode] = useState(false);
    // const openEditMode = () => setEditMode(editMode => !editMode);

    const deleteClick = () => {
        fetch(`/topics/${topic.id}/chats/${id}`, {
            method: "DELETE",
        })
        deleteComment(id)
    }

    return (
        <div>
            <ul>
                <p><strong>{ chat.user.username }:</strong> { chat.content }</p>
            </ul>
            {user && user.username === chat.user.username && (
                <div className="chat-btn">
                <button className="delete-btn" onClick={deleteClick}>Delete</button>
                <button className="edit-btn" onClick={() => setEditMode(editMode => !editMode)}>Edit</button>
                </div>
            )}
            { editMode && <ChatEdit chat={chat} topic={topic} editChat={editChat} editMode={editMode} setEditMode={setEditMode} /> }
        </div>
    )
}

ChatEdit.js

import { useState, useContext } from "react";
import { ErrorsContext } from "../context/ErrorsContext";
import Errors from "../errors/Errors";

function ChatEdit({ chat, topic, editChat, editMode, setEditMode }) {
    const { setErrors } = useContext(ErrorsContext);
    const [content, setContent] = useState(chat.content);

    const handleSubmit = (e) => {
        e.preventDefault();
        const editComment = {
            content: content
        }
        fetch(`/topics/${topic.id}/chats/${chat.id}`, {
            method: "PATCH",
            headers: { 
                "Accept": "application/json",
                "Content-Type": "application/json" 
            },
            body: JSON.stringify(editComment)
        })
        .then(resp => resp.json())
        .then(data => {
            if (data.errors) {
                setErrors(data.errors)
            } else {
                editChat(data)
                setErrors([])
                setEditMode(!editMode)
            }
        })
    }

    return (
        <form className="post-form" onSubmit={handleSubmit}>
            <div className="new-post">
            <textarea className="chat-textarea" type="text" name="content" placeholder="Write your comment." value={content} onChange={(e) => setContent(e.target.value)} /><br/>
            <button type="submit">SEND</button>
            </div>
            <Errors />
        </form>
    )
}

export default ChatEdit;

I am trying to get the edited comment to update once I submit the form. It’s updating but not until I refresh the screen.

2

Answers


  1. The only explanation for this, is that when you update the chats state in Content from inside ChatEdit, the parent component ie Contentrerenders but still passes the same object as chat props to ChatCard.

    without including how you pass chat from Content to ChatCard I can’t help you fix this, but at least, you understood what’s going on.

    Login or Signup to reply.
  2. It seems that the issue might be related to how you’re updating the chats state in the Content.js component.

    Currently, in the editChat function, you’re mapping over the chats array to find the comment with a matching id and update it with the newComment. However, in your mapping function, you’re comparing topic.id with newComment.id, which seems incorrect. It should be chat.id instead.

    To fix this, you can modify the editChat function as follows:

    const editChat = (newComment) => {
      const updatedChatList = chats.map(chat => {
        if (chat.id === newComment.id) { // Compare chat.id with newComment.id
          return newComment;
        } else {
          return chat;
        }
      });
      setChats(updatedChatList);
    };
    

    By comparing chat.id with newComment.id, the correct comment should be updated in the chats array, and the state should be updated accordingly.

    If this doesn’t solve the issue, there might be other factors at play, such as how the chats state is initially populated or how it’s passed down to the ChatCard component. In that case, providing more details or the surrounding code would be helpful in further troubleshooting.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search