I have a form that I would like to submit (POST) when a function is called outside the form and without a button (It works with a button).
I have tried to use this: document.getElementById('liked').submit();
But then it just pastes this into the url: http://localhost:3000/?postId=108&userId=1
I have tried to put method="post" in the form tag, but then it says “CANNOT POST”
The post is done with Axios.
Besides that, I would like it to NOT reload the page/component
This is my form:
<form id="liked" name="liked" onSubmit={handlePost}>
<input hidden name="postId" id="postId" value={product.id} />
<input hidden name="userId" id="userId" value={currentUser.id} />
</form>;
This is my callback that call the Axios post function:
const handlePost = useCallback((event) => {
event.preventDefault();
context.postBookmark(event.target);
});
This is where I would like the form to be submitted:
const onSwipe = (direction) => {
if (direction == "right") {
// SUBMIT HERE
document.getElementById("liked").submit();
}
}
When you call the submit() method of the form it directly submits the form.
It does not trigger a submit event. The submit handler won't be called. preventDefault will not be called. context.postBookmark will not be called.
If you want to call context.postBookmark from outside the form, then just do it directly without starting a regular form submission.
context.postBookmark(document.getElementById("liked"));
Aside: Direct DOM access is not recommended with using React. Instead use a reference or (better) store the data in the state and read it from there).