Reputation: 95
I have a form component and after filling the form and putting all data, if you press submit it goes to proectaction and does an axios api post call. if successful I want it to go back to "/dashboard"
/* eslint-disable comma-dangle */
/* eslint-disable arrow-parens */
import axios from 'axios';
// import { useHistory } from 'react-router-dom';
import { GET_ERRORS } from './types';
const createProject = (project) => async dispatch => {
await axios.post('http://localhost:8080/api/project', project)
.catch((error) => {
dispatch({
type: GET_ERRORS,
payload: error.response.data
});
});
};
export default createProject;
Upvotes: 1
Views: 80
Reputation: 344
You could do something like this:
EDIT: make sure you are passing the history prop to the action, or make the push when you're using the action on the component.
const createProject = (project, history) => async dispatch => {
try {
await axios.post('http://localhost:8080/api/project', project)
history.push('/') // <---- Make the push here only after post success.
} catch(error) {
dispatch({
type: GET_ERRORS,
payload: error.response.data
});
}
};
try catch block then a history push to a different route.
alternatively:
const createProjectHandler = async () => {
createProject(project).then(() => {
props.history.push('/')
})
}
this only works when you're returning the axios call. I'm not sure if its the same with async and await.
Upvotes: 1