3

I am trying to reset its field of a form after an async function completes execution. However, when the async function completes its instructions, I found that the e.currentTarget (where e is the React.FormEvent<HtmlFormElement> object). Here is the code please review and let me know what was wrong in my code:

onAddFormSubmitted(e: React.FormEvent<HTMLFormElement>): Promise<void> { e.preventDefault(); const formdata = new FormData(e.currentTarget); // e.currentTarget.reset(); // it worked here if (formdata) { const book: Book = { title: formdata.get("booktitle") as string, author: formdata.get("authorname") as string, } addBook(book).then((doc) => { book.id = doc.id; this.props.onBookCreated(book); e.currentTarget.reset(); // e.currentTarget becoming null at this point. Why? }); } } 

I am trying to reset form element after the asynchronous function call. But, the currentTarget object becomes null.

1

2 Answers 2

3

Keep a reference to the desired target:

onAddFormSubmitted(e: React.FormEvent<HTMLFormElement>): Promise<void> { e.preventDefault(); const currentTarget = e.currentTarget; const formdata = new FormData(currentTarget); if (formdata) { const book: Book = { title: formdata.get("booktitle") as string, author: formdata.get("authorname") as string, } addBook(book).then((doc) => { book.id = doc.id; this.props.onBookCreated(book); currentTarget.reset(); // e.currentTarget becoming null at this point. Why? }); } } 

The same event object is used throughout the capturing and bubbling phases and currentTarget is updated on each step. Once bubbling is complete, currentTarget is set to null. Your async code executes after bubbling.

This is how native events work in the DOM, this is not related to React.

See also How come my event.currentTarget is changing automatically?

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

Comments

0

i have also stumbled upon this and have not many ideas. capturing it before the async operation seemed to work.

 async function submitForm(e: React.FormEvent<HTMLFormElement>) { e.preventDefault(); const { currentTarget } = e; const resetable = currentTarget; const formData = new FormData(currentTarget); await upload(formData); resetable.reset(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.