Search code examples
reactjsreduxfetchredux-thunkdispatch

React onClick delete dispatch won't send second dispatch request after response received


In a component I have a button that onClick dispatches a deleteQuestion action that sends a fetch backend delete request, and when the response is received is supposed to call another action to update the Redux store.

However, since it's an onClick event, the deleteQuestion thunk function does not work like a traditional dispatch request made from ComponentWillMount and instead returns an anonymous function with a dispatch parameter that never is called. Therefore, I'm required to call the dispatch twice simultaneously in the onClick method like so:

   handleDelete = () => {
    const { questionId } = this.props.match.params
    const { history } = this.props
    deleteQuestion(questionId, history)(deleteQuestion); //calling method twice
   }

While this approach is effective for trigging the delete request to the Rails backend, when I receive the response, the second dispatch function that I have embedded in the deleteQuestion action -- dispatch(removeQuestion(questionId)) -- won't trigger to update the Redux store. I've tried placing multiple debuggers in the store and checking console and terminal for errors, but nothing occurs.

I've read through the Redux docs and other resources online and from what I've been able to find they all say it should be possible to include a second dispatch call in a .then request. While it's possible to do this in get, post, and patch requests, I can't figure out why it won't work in a delete request.

The thunk call I make is:

 export function deleteQuestion(questionId, routerHistory) {
   return (dispatch) => {
     fetch(`${API_URL}/questions/${questionId}`, {
       method: 'DELETE',
     }).then(res => {
       dispatch(removeQuestion(questionId))
     })
   }
 }  

And the github is: https://github.com/jwolfe890/react_project1/blob/master/stumped-app-client/src/actions/questions.js

I'd really appreciate any insight, as I've been trying to get passed this for two days now!


Solution

  • You are calling the action deleteQuestion directly instead of having your store dispatch the delete question action for you. You should instead call the deleteQuestion from your props that is already mapped to dispatch:

    handleDelete = () => {
      const { questionId } = this.props.match.params
      const { history } = this.props
      this.props.deleteQuestion(questionId, history);
    }
    

    If you pass in an object as mapDispatchToProps each element is dispatch call. In other words your mapDispatchToProps is equivalent to:

    (dispatch) => ({ 
        deleteQuestion: (...params) => dispatch(deleteQuestion(...params)) 
    })