Skip to content

Instantly share code, notes, and snippets.

@nilshartmann
Created June 29, 2021 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilshartmann/0ac09d01a146e8ecfaed8d476fb8d900 to your computer and use it in GitHub Desktop.
Save nilshartmann/0ac09d01a146e8ecfaed8d476fb8d900 to your computer and use it in GitHub Desktop.

Routing after handling an action in Redux

Note: this are simplified example, concept only, not correct syntax etc.!

Approach one: use history object in thunk action creator

// my-app-history

import { createHashHistory as createHistory, History } from "history";
export default createHistory();
// my-actions.js
import history from "./my-app-history"

export function login(username) {
  return async (dispatch) => {
  
    // do some (async) things
    const userData = await fetch(...); 
    
    // dispatch one or more actions
    dispatch(userLoggedIn(userData));
    
    // change location
    history.push("/welcome-user");
  }
}

// Login component
export default function Login() {
  onLoginClick() {
    dispatch(login(username));
  }
  
  return <button onClick={onLoginClick}>Login</button>
}

Approach 2: 'await' dispatch and use history in your component

// my-actions.js
export function login(username) {
  return async (dispatch) => {
  
    // do some (async) things, same as above...
    const userData = await fetch(...); 
    
    dispatch(userLoggedIn(userData));
    
    // no history here!
  }
}
// Login component
export default function Login() {
  const history = useHistory();
  
  async onLoginClick() {
    // await action processing
    await dispatch(login(username));
    
    // re-route here
    history.push("/welcome-user");
  }
  
  return <button onClick={onLoginClick}>Login</button>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment