1

I've learned of 2 methods to redirect to a different page after executing an async action with Redux Thunk:

1-Method: Passing "history" object to the async action as argument.

In your component you define the "history" object with "useHistory" hook and pass it to your async action:

function Register(){
    const history = useHistory()
    const dispatch = useDispatch()
    
    function registerHandler(){
        dispatch(registerAsync(registerForm, history))\
    }

    return (
        // JSX Code
        <button onClick={registerHandler}>Register</button> 
    )
}

Then in your async action, you can use "history.push()" to redirect:

export function registerAsync(data, history){
    return async function (dispatch) {
        try {
            const response = await Axios.Post('api/register/', data)
            history.push('/register_success')
        } catch (e) {
            dispatch(registerError(e))
        }
    }
}

2-Method: Using the < Redirect > component that gets conditionally rendered depending on a Redux store value:

In the component you return conditionally if a store value is true:

function Register(){
    const dispatch = useDispatch()
    const registerSuccess = useSelector((store) => store.auth.registerSuccess)
    
    function registerHandler(){
        dispatch(registerAsync(registerForm, history))\
    }
    
    
    if (registerSuccess) {
        return <Redirect push to="/register_success"/>
    }

   return (
        // JSX Code
        <button onClick={registerHandler}>Register</button>
    )
}

And inside our Async action we dispatch an action that sets the "registerSuccess" to true:

export function registerAsync(data){
    return async function (dispatch) {
        try {
            const response = await Axios.Post('api/register/', data)
            dispatch(registerSuccess())
        } catch (e) {
            dispatch(registerError(e))
        }
    }
}

Reducer:

 case actionTypes.REGISTER_SUCCESS:
            newState.registerSuccess = true
            return newState

Does anyone know which of the 2 methods is correct and why?

Many thanks!

Alvaro Bataller
  • 673
  • 5
  • 15
  • If using react-router-dom then I think option 3 [connected-react-router](https://github.com/supasate/connected-react-router). Allows you to dispatch navigation action. – Drew Reese Nov 20 '20 at 08:35

0 Answers0