Dog Dog - 1 year ago 169
React JSX Question

Issues sending Fetch delete request in React to Rails API

I'm able to send get and put methods fine, but am surprisingly not able to send a delete fetch request from my Redux action to my Rails backend. This is even more perplexing because in Postman I'm able to hit the Destroy route fine. I've searched all over for a fix, but haven't found anything that works. I have an onClick function that triggers the Redux action that sends this request:

export const deleteQuestion = (questionId, routerHistory) => {
return dispatch => {
return fetch(`${API_URL}/questions/${questionId}`, {
method: 'DELETE',
}).then(response => {
dispatch(removeQuestion(questionId));
routerHistory.replace(`/`);
})
.catch(error => console.log(error));
};
};


I've checked numerous times to make sure the syntax and route is fine. questionId is also the correct question ID. However, no matter what I do, the Destroy method in the Questions controller won't recognize the request. I've checked the route in Rails and it exists. I don't get any errors, no request is ever sent to the server, and nothing is returned, not in terminal, the console, or anything.

This is the Github account: https://github.com/jwolfe890/react_project1

I'd really appreciate any insight anyone has. Thank you!

Answer Source

Your deleteQuestion method returns an anonymous function with a dispatch parameter which never seems to be called (Calling code). Only deleteQuestion is called but not the function returned by it.

Because it is called by a click handler I'd say you actually want something like this:

export const deleteQuestion = (questionId, routerHistory) => {   
  fetch(`${API_URL}/questions/${questionId}`, {
     method: 'DELETE',      
  }).then(response => {
     dispatch(removeQuestion(questionId));
     routerHistory.replace(`/`);
  })
  .catch(error => console.log(error));
};

Or if you want to return the promise, you could of course change it to:

export const deleteQuestion = (questionId, routerHistory) => {   
  return fetch(`${API_URL}/questions/${questionId}`, {
     method: 'DELETE',      
  }).then(response => {
     dispatch(removeQuestion(questionId));
     routerHistory.replace(`/`);
  })
  .catch(error => console.log(error));
};

If you want to dynamically inject the dispatch function, you could leave your original code, but would have to call the method like this:

deleteQuestion(this.state.question.id, history)(myDispatchMethod);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download