Search code examples
reactjsreact-routerreduxredux-thunkreact-router-redux

Redux - Change URL when an async action is dispatched


In my React/Redux application, I have some async actions. Let's say a user initiates a getData request to the server. Immediately a GET_DATA_REQUEST is being dispatched and the getData AJAX call is on its way to the server.

Upon success or failure, a GET_DATA_SUCCESS or GET_DATA_FAILURE actions are dispatched accordingly and the data is rendered to the UI.

Now, I want my application to push history state (using react-router-redux) as a reaction to the AJAX callback. Meaning, upon success, the users is "redirected" to another URL (route) the displays a different module that depends on the newly received data.

I realize it's a very bad idea to have this functionality in the reducer, as it won't be pure anymore (URL change is a side effect).

Any thoughts?

Thanks


Solution

  • I believe this is a good way to handle your situation.

    First of all, you should add a new property in your reducer to know if you want to redirect or not.

    Something like this

    const initialState = {
       ...
       redirect : false // You could use a String with the new url instead of true/false
       ....
    }
    
    switch ...
    case GET_DATA_SUCCESS:
           return {
                ...state,
                redirect:true,
           }
    case GET_DATA_FAILURE;
          return {
              ...state,
              redirect:false
          }
    

    Then, in the component connected to your reducer, you should check the value of "redirect" in the componentDidUpdate function.

    componentDidUpdate(){
            let {redirect} = this.props.yourReducerState;
            if(redirect === true){
                this.context.router.push("new-url");
            }
        }
    

    Finally, you should reset "redirect" on componentWillUnmount

    Hope it helps!