Last active
August 25, 2020 18:49
-
-
Save vladi-strilets/ed81634301f8e6221eb71c068b25ca59 to your computer and use it in GitHub Desktop.
Dispatch redux action on history location route change with React Router v5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// HistoryListener.js | |
import React, { useEffect, useState } from "react"; | |
import { connect } from "react-redux"; | |
import { useHistory } from "react-router-dom"; | |
import { someAction } from "./../redux/someReducer/actions"; | |
const HistoryListener = ({ | |
children, | |
// MDTP | |
someAction, | |
}) => { | |
const [isFirstRender, setIsFirstRender] = useState(true); | |
const history = useHistory(); | |
// locations listener | |
useEffect(() => { | |
console.log("Location:", history.location.pathname) | |
someAction(); | |
setIsFirstRender(false); | |
return history.listen((location) => { | |
console.log("Location:", location.pathname) | |
someAction(); | |
}); | |
}, [history]); | |
// if is the first time render, show loading | |
if (isFirstRender) { | |
return <p>Loading...</p>; | |
} | |
return children; | |
}; | |
const mapDispatchToProps = (dispatch) => ({ | |
someAction: () => dispatch(someAction()), | |
}); | |
export default connect(null, mapDispatchToProps)(HistoryListener); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment