Wolf_Tru
Wolf_Tru

Reputation: 563

React/JS - Creating a conditional on the server response of action call

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

Answers (1)

Blue
Blue

Reputation: 22911

You have 2 ways of doing this:

  1. A callback that you can pass into your dispatch action:
//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
      })
  );
}
  1. Ideally, you should be doing this via your redux actions/reducers:

//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

Related Questions