skip to Main Content

I am still struggling to grasp the whole concept of react yet. I want to implement a Query form where user will add a reply. But from when I’ve done, i have to refresh the page to see the replies which a good UX. Here’s my code

const { id } = useParams();
    
const [loading, setLoading] = useState(false);

const queryItem = Queries.find((item, indx) => indx === parseInt(id));

// ********************************************************REPLY QUERY
const onSubmit = (e) => {
    e.preventDefault();
    setLoading(true);

    const params = JSON.stringify({
        id: userID
        message: queryMessage,
    });

    Axios(`${api.baseURL}/replyquery`, {
        method: "POST",
        data: params,
    })
        .then((res) => {
            setLoading(false);
            setQueryMessage("");
        })
        .catch((err) => {
            console.log(err);
            setLoading(false);
        });
};

Below is my query render

<div className=" px-4">
    {queryItem?.reply?.map((item, index) => (
        <div key={index}>
            <div className="">
                <p className="">
                    <span>
                        <IoArrowRedo className="text-black" />
                    </span>
                    Replied by: {item?.replied_by?.name}
                </p>
                <p className="">{item?.reply_date}</p>
            </div>

            <p>{item?.reply_message}</p>
        </div>
    ))}
</div>;

2

Answers


  1. You can use usestate to re-render. setQueryItem after res ok.

    const [queryItem, setQueryItem] = useState(Queries.find((item, indx) => indx === parseInt(id)));
    
    const onSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
    
        const params = JSON.stringify({
            id: userID,
            message: queryMessage,
        });
    
        try {
            const res = await Axios(`${api.baseURL}/replyquery`, {
                method: "POST",
                data: params,
            });
    
            setLoading(false);
            setQueryMessage("");
    //setQueryItem...
        } catch (err) {
            console.log(err);
            setLoading(false);
        }
    };
    
    Login or Signup to reply.
  2. The first thing is to create a state to store the submitted reply.

    const [reply, setReply] = useState("");
    

    Then in your form submission function, update the reply state variable with the submitted value, something like this

    const handleSubmit = (event) => {
      event.preventDefault();
      // ... code to submit reply to server ...
      setReply("Your reply has been submitted successfully.");
    }
    

    And finally just call it where you want

    {reply && <p>{reply}</p>}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search