i'm newbie for React maybe for english too. How can i redirect after form submitted ?
function Test() {
const { register, handleSubmit } = useForm()
const onSubmit = data => {
fetch(`http://localhost:4000/signup`)
//Here i want to redirect after signup
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
....
</form>
);
}
fetch can be used with either callbacks or promises, you need to wait for the asynchronous request to finish before you redirect.
This is a simply callback example, it assumes you do not need to access the response body of the request or need to check the response status.
function Test() {
const { register, handleSubmit } = useForm()
const onSubmit = data => {
fetch(`http://localhost:4000/signup`)
.then(resp => {
// Navigate here, either:
// use browser (not nice if SPA)
window.location = "http://www.url.com/path";
// use connected react router
// implementation specific
// e.g. this.props.push("/path");
});
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
....
</form>
);
}
If you're familiar with Promises and async await, you could use the following
function Test() {
const { register, handleSubmit } = useForm()
const onSubmit = async (data) => {
await fetch(`http://localhost:4000/signup`);
// navigate here
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
....
</form>
);
}
Ideally you should look to handle side effects like these via some kind of middleware, for example Redux Thunk, Promise, Sagas or Observables. This removes unnecessary business logic from your components, allows for cleaner testing and better separation of concerns.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments