Reputation: 359
I'm a newbie to Promises and React. I'm using redux-thunk in my action creators to resolve promises and I'm calling the action creators from my component. How do I route to a different URL after successful or unsuccessful request completion? I'm attaching the code for a delete function action creator.
Should I set the state with a parameter (routeTo) when I dispatch it, on success?
Here's the delete function:
export function deletePost(id){
var request = axios.delete(`${ROOT_URL}posts/${id}${API_KEY}`);
return function(dispatch){
request.then((response)=>{
console.log("I deleted"+response.data.title);
}).catch((error)=>{
console.log("DELETE_ERROR: "+JSON.stringify(error));
});
}
}
I'm calling this function from an onclick function in my component.
deletePost(){
this.props.deletePost(this.props.params.id);
}
Upvotes: 7
Views: 7816
Reputation: 4039
The best way I have found to do routing with redux is to consider the URI part of my state, and store it within redux. There is an excellent library react-router-redux that will do this for you.
Once you have react-router-redux setup, then you can just dispatch actions to change location, so your thunk would look like:
import { push } from 'react-router-redux';
export function deletePost(id){
var request = axios.delete(`${ROOT_URL}posts/${id}${API_KEY}`);
return function(dispatch){
request.then((response)=>{
console.log("I deleted"+response.data.title);
dispatch(push('/delete-success-uri'));
}).catch((error)=>{
console.log("DELETE_ERROR: "+JSON.stringify(error));
dispatch(push('/delete-fail-uri'));
});
}
}
Upvotes: 14