Home > database >  Trigger Form Submission from inside React useEffect hook?
Trigger Form Submission from inside React useEffect hook?

Time:02-04

In my React component, I need to listen for a value to change then trigger a form to be submitted.

Currently I'm using a useEffect hook to listen for changes to a state variable mediaBlob,

import { useEffect, useState } from "react";

export function Foo({
  handleSubmit,
  ...props
}) {

  let { mediaBlob, setMediaBlob } = useState(null)

  useEffect(() => {
    if (mediaBlob) {
      // how to trigger the form submission here?
      // Cant call the form's handleSubmit() method without an event
    }
  }, [mediaBlob]);

but I cant call the form's handleSubmit function because the function needs to accept an event object e.

async function handleSubmit(e) {
  e.preventDefault()
  // ...
}


return (
  <form onSubmit={handleSubmit}>
    <Foo handleSubmit={handleSubmit} />
  </form>
)

Is it still possible to trigger the form submission from within the useEffect hook?

CodePudding user response:

Extract code after e.preventDefault() into another function and call that from useEffect. In case you need to get form Data from the event, you also need to use ref to get reference to form element and extract needed data. You can also use controlled inputs.

CodePudding user response:

Yes, It's possible to trigger form submission form within useEffect using useRef here is sample code:

import { useEffect, useState, useRef } from "react";

export function Foo({
  handleSubmit,
  ...props
}) {
  const { mediaBlob, setMediaBlob } = useState(null)
  const ref = useRef(null);

  useEffect(() => {
    if (mediaBlob) {
      ref.current.submit();
    }
  }, [mediaBlob]);

  return (
    <form onSubmit={handleSubmit} ref={ref}>
      {/* form content */}
    </form>
  )
}

return (
  <form onSubmit={handleSubmit}>
    <Foo handleSubmit={handleSubmit} />
  </form>
)
  • Related