Redirect to Url After Form Submit in React

Redirect after submit in React

By assuming you are using react-router v4, you will want to use history object to navigate.

import { withRouter } from 'react-router';
...

handleSubmit = () => {
...
this.props.history.push('/moneyform');
}

render() {
return (
<ReactFragment>
<div>
...
</ReactFragment>
)
}


export default withRouter(confirmWithdraw);

React.Js how to redirect on form submit?

From what you posted, the reason you don't redirect upon post deletion is because the backend prevents it from happening.

  1. to redirect the user after he has deleted the post, if you are using React-router-dom version 6, you need to use useNavigate(), because useHistory and have been replaced by useNavigate(), so this is how you would redirect the user if he deletes something.
    const navigate = useNavigate();
const onSubmit = async (event: any) => {
event.preventDefault();
try {
const url: string = `http://localhost:8000/api/posts/${postID}`;
await sendRequest(url, 'DELETE');
closeModal(event);
navigate(`/`);
} catch (err: any) {}
}

  1. The reason your post doesn'T redirect is because, when you send the DELETE request the backend sends back an error, but before the error happens the Post gets deleted from the database, and its happening in the second try..catch block. The error happens here ->
    post.creator.posts.pull(post);  //THIS IS WERE THE ERROR HAPPENS

The error happens because you are searching for creator in the Post Schema, but Post Schema doesn't have creator so it panics and throws an error, instead it has creator_id and creator_name, so you should replace it like this, if you are searching for user by ID

   post.creator_id.posts.pull(post);

So your code on the backend should look like this (Its totaly same expect the post.creator_id.posts.pull(post)

export const deletePost = async (req: Request, res: Response, next: NextFunction) => {
const postID = req.params.postID;
let post: any;

try {
post = await POST.findById(postID).populate('creator_id');
} catch (err: any) {
console.log(err.message)
const error = {
message: "Couldn't delete POST !",
code: 500
};
return next(error);
}

if(!post){
const error = {
message: "Post doesn't exist, so it could not be deleted !",
code: 404
};
return next(error);
}
try{
await post.remove();
post.creator_id.posts.pull(post);
await post.creator_id.save();

}catch(err){
const error = {
message: "Couldn't delete POST from DATABASE!",
code: 500
};

return next(error);
}
res.status(200).json({message: "Post deleted !"});
}

How can i redirect after submit form React

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.



Related Topics



Leave a reply



Submit