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.
- 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) {}
}
- 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
Mobile Safari Sometimes Does Not Trigger the Click Event
I Want a Code to Fill in the Form Automatically
How to Calculate the Sum of Table Column in Angular 2+
Javascript: How to Redirect a Page After Validation
Update Value in Localstorage Array by Existing Key
How to Get the Ajax Response from Success and Assign It in a Variable Using Jquery
Stop Just One Dropdown Toggle from Closing on Click
How to Trigger Click Event on Select Element (Not Change)
Angular - How to Get Result of a Json Object
React-Native React-Navigation Undefined Is Not an Object (Evaluating 'S.Value.Startswith')
Drawing Curved Svg Arrow Lines from Div to Div
How to Pass Data from Flask to JavaScript in a Template
How to Modify Chartjs Tooltip So I Can Add Customized Strings in Tooltips
Cannot Read Property of Undefined @Viewchild Not Working Angular 5
React Native How to Call Multiple Functions When Onpress Is Clicked
Useselector Not Updating When Store Has Changed in Reducer. Reactjs Redux
Javascript Form Submit - Confirm or Cancel Submission Dialog Box