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);
}
We can redirect after a Redux action is committed. To do that, we install the history package. Then we can create a function like: import { createBrowserHistory } from 'history'; const browserHistory = createBrowserHistory(); const actionName = () => (dispatch) => { axios .
Thunks are the standard approach for writing async logic in Redux apps, and are commonly used for data fetching. However, they can be used for a variety of tasks, and can contain both synchronous and asynchronous logic.
Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store's dispatch method, which is then used to dispatch regular synchronous actions inside the function's body once the asynchronous operations have been completed.
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'));
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With