skip to Main Content

Hi StackOverflow Country,

I was wondering is someone could be so kind and explain what the bug in my code is >> specifically the fact that the setPostList([…postList, post]) does not seem to work correctly

I am not able to successfully Lift the State Up ? can you please give me your thoughts why my code is not working
0 upvotes
Mohamed · Lecture 27 · A few seconds ago
Hello Sir can you please tell me where I went wrong ?

I dont think the postList array is being updated I tried it using the spread setPostList([…postList,post]) but that did not work, I also tried pushing using a call back function into the array but that did not work either, can you help me identify the issue here …

// Here is my Modal

import { useState } from "react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
 
const Modal = (props) => {
  const [author, setAuthor] = useState("");
  const [body, setBody] = useState("");
 
  return (
    <>
      <AlertDialog>
        <AlertDialogTrigger
          style={{
            border: "1px solid black",
            padding: "10px 40px",
            borderRadius: "4px",
          }}
        >
          Create An Announcement
        </AlertDialogTrigger>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Publish A New Announcement:</AlertDialogTitle>
 
            <input
              type="text"
              placeholder="Your Name"
              onChange={props.changeMessageAuthor}
            />
            <textarea
              type="text"
              rows={5}
              placeholder="Type your announcement here ..."
              onChange={props.changeMessageBody}
            />
 
            <AlertDialogDescription>
              <span className="text-emerald-600 text-xl font-black">
                Review Your Announcement:
              </span>
              <br />
              <span className="font-black">
                Author:
                <br />
                {author}
                {props.author}
              </span>
              <br />
              <span className="font-black">Announcement:</span>
              <br /> {props.body}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={props.addAnnouncement}>
              Publish
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};
 
export default Modal;

// Here is my PostList

//Here is my PostList

import postcss from "postcss";
import { useState, useEffect } from "react";
import Modal from "./Modal";
 
const PostList = () => {
  const [body, setBody] = useState("");
  const [author, setAuthor] = useState("");
  const [postList, setPostList] = useState([]);
  const [post, setPost] = useState({});
 
  const handleMessageBody = (event) => {
    setBody(event.target.value);
  };
 
  const handleMessageAuthor = (event) => {
    setAuthor(event.target.value);
  };
 
  const handleAddingAnnouncement = (event, author, body) => {
    event.preventDefault();
    setPost({ author: author, body: body });
    setPostList([...postList, post]);
    console.log(postList[0]);
  };
 
  return (
    <>
      <hr />
      <br />
      <Modal
        author={author}
        body={body}
        changeMessageAuthor={handleMessageAuthor}
        changeMessageBody={handleMessageBody}
        addAnnouncement={handleAddingAnnouncement}
      />
      <br />
      {postList.length > 0 && postList.map((e) => e.body)}
      {postList.length === 0 && <h1>loading...</h1>}
    </>
  );
};
 
export default PostList;
 

2

Answers


  1. Chosen as BEST ANSWER

    I made a change to how I am handling submitting and now it works - also I know preventDefault() was in the submit to begin with

      // const handleAddingAnnouncement = (event, author, body) => {
      //   event.preventDefault();
      //   setPostList((prev) => {
      //     const myList = [...prev];
      //     myList.push({
      //       id: Math.floor(Math.random() * 10000),
      //       author: author,
      //       body: body,
      //     });
      //     console.log
      //     return myList;
      //   });
      // };
    
      const handleAddingAnnouncement = (event) => {
        event.preventDefault();
        setPostList([
          ...postList,
          { id: Math.floor(Math.random() * 10000), author: author, body: body },
        ]);
      };


  2. It seems like you’re encountering a common issue in React regarding the asynchronous nature of state updates. The problem lies in how you’re handling the state update in handleAddingAnnouncement.

    When you call setPostList([...postList, post]), you’re attempting to update postList with the current value of post. However, since setPostList is asynchronous, the state update may not have happened by the time you access postList again in the next line. As a result, you’re not getting the updated value of postList.

    To fix this, you can use the functional update form of setPostList, which takes a function as an argument. This function receives the current state as its argument, allowing you to safely update state based on the previous state:

    const handleAddingAnnouncement = (event, author, body) => {
      event.preventDefault();
      const newPost = { author: author, body: body };
      setPostList(prevPostList => [...prevPostList, newPost]);
    };
    

    By using the functional form, you ensure that you’re always working with the latest state. This should resolve the issue you’re encountering with the state not updating correctly.

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