Reputation: 563
I have a modal to add a todo item that resets after submission but it also resets if the submission fails, How do I make it so my modal stays open and user can see the errors they made?
//modal component
onSubmit = e => {
e.preventDefault();
const newTask = {
task: this.state.task
};
this.props.addTask(newTask)
// sudo code below
if(this.props.addTask(newTask === 200 status success or something){
this.setState({task: "" })
//Close modal
this.toggle();
}
}
// action file
export const addTask = (task) => dispatch =>{
axios.post('/api/users/newtask', task )
.then(res =>
dispatch({
type: ADD_TASK,
payload: res.data
})
).catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
}
Not sure if it helps but I'm using axios for the api calls
Upvotes: 0
Views: 59
Reputation: 22911
You have 2 ways of doing this:
//modal component
onSubmit = e => {
e.preventDefault();
const newTask = {
task: this.state.task
};
this.props.addTask(newTask, () => {
this.setState({task: "" })
//Close modal
this.toggle();
});
}
// action file
export const addTask = (task, successCallback) => dispatch =>{
axios.post('/api/users/newtask', task )
.then(res => {
dispatch({
type: ADD_TASK,
payload: res.data
});
if (typeof successCallback === 'function') {
successCallback(res.data);
}
)
).catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
}
//modal component (Or don't render the modal at all at the parent component)
...
render() {
if (!this.props.showModal) {
return null;
}
}
// Action:
dispatch({
type: ADD_TASK,
payload: res.data
});
//Reducer
function reducer(state = initialState, action) {
switch (action.type) {
case ADD_TASK:
return Object.assign({}, state, {
tasks: [...state.tasks, action.task],
showModal: false, // <== Set show modal to false when the task is done.
})
default:
return state
}
}
Upvotes: 1