I have created a react app that takes a picture file and some other inputs in a form and sends them to API with fetch "post". Everything works great, api does its job and returns the correct response, which shows in the alert function. However, right after the fetch is completed, the page is refreshed automatically. I want to redirect to another page after the fetch, with the response data, but it returns back to the form page because of this issue. Here's my code:
export default function Miyuki() {
const { register, handleSubmit } = useForm()
const onSubmit = async (data) => {
const formData = new FormData()
formData.append("picture", data.picture[0])
formData.append("row", data.row)
formData.append("column", data.column)
const res = await fetch(baseApiUrl + "miyuki/prev", {
method: "POST",
body: formData
}).then(res => res.json())
.then(res => {
alert(JSON.stringify(res))
})
}
return (
<React.Fragment>
<Toolbar></Toolbar>
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('picture', { required: true })} type="file" />
<input {...register('column', { required: true })} type="number" min="1" max="50" />
<input {...register('row', { required: true })} type="number" min="1" />
<button>Submit</button>
</form>
</React.Fragment>
);
}
I have already tried stuff like event.preventDefault(). But the problem is not related to form. It refreshes after fetch post is completed. Is there a way to prevent this refresh, or is there a way that I can redirect to another page with the response from the fetch without it coming back to this page right after going to the target page?
Nevermind, solved it. Problem wasn't caused by fetch or form. Turns out, in React during development, if you make any changes inside the "public" folder, the page will refresh. Getting a production build solved the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With