The form submission is not being triggered automatically as expected

I am working on a chat application and I have a feature where users can select prompts. When a user selects a prompt, you want the chat input to automatically populate with the selected prompt and submit the form.

However, I am encountering an issue where the form is not being submitted automatically when the input changes after a prompt is selected. I’ve tried to programmatically dispatch a submit event on the form and directly call the onSubmit function from a useEffect hook, but neither approach is working as expected.

The main challenge here is dealing with the asynchronous nature of state updates in React. When I update the selectedPrompt state, it doesn’t immediately re-render the component. Therefore, the useEffect hook might not have the latest selectedPrompt value when it tries to click the submit button.

import React, { useState, useEffect, useRef } from "react";
import { Button } from "../button";
import FileUploader from "../file-uploader";
import { Input } from "../input";
import UploadImagePreview from "../upload-image-preview";
import { ChatHandler } from "./chat.interface";
import { ArrowUp } from 'lucide-react';

interface ChatInputProps extends Pick<
  ChatHandler,
  "isLoading" | "input" | "onFileUpload" | "onFileError" | "handleSubmit" | "handleInputChange"
> {
  multiModal?: boolean;
  selectedPrompt: string;
  setSelectedPrompt: (prompt: string) => void; 
}

export default function ChatInput({
  isLoading,
  input,
  onFileUpload,
  onFileError,
  handleSubmit,
  handleInputChange,
  multiModal,
  selectedPrompt,
  setSelectedPrompt 
}: ChatInputProps) {
  const [imageUrl, setImageUrl] = useState<string | null>(null);
  const formRef = useRef<HTMLFormElement>(null);

  useEffect(() => {
    if (selectedPrompt) {
      handleInputChange({ target: { value: selectedPrompt } } as React.ChangeEvent<HTMLInputElement>);
      if (formRef.current) {
        formRef.current.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));
      }
      setSelectedPrompt('');
    }
  }, [selectedPrompt]);

  const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (selectedPrompt) {
      handleSubmit(e, { data: { imageUrl } });
      setImageUrl(null);
      setSelectedPrompt(''); 
    } else {
      handleSubmit(e);
    }
  };

 

  return (
    <form ref={formRef} onSubmit={onSubmit}>
        <Input
          name="message"
          placeholder=""
          value={input}
          onChange={handleInputChange}
        />
        <button
          type="submit"
        >
        </button>
    </form>
  );
}

The selected prompt is passed into the input as soon as the updates, the form is supposed to submitted as well but its having issues.

tried debugging using logging and debugging also tried stepping through the code

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật