1

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?

1
  • how does mediaBlob get changed? Commented Feb 3, 2023 at 6:01

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.