Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use redux thunk to redirect after success or error?

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);
}
like image 770
ishan Vadwala Avatar asked Mar 24 '17 22:03

ishan Vadwala


People also ask

Can I redirect from Redux action?

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 .

Is Redux thunk still used?

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.

How does Redux thunk Change Action creators?

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.


1 Answers

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'));
        });
    }
}
like image 89
Alex Young Avatar answered Sep 17 '22 23:09

Alex Young