Skip to content

Instantly share code, notes, and snippets.

@vladi-strilets
Last active August 25, 2020 18:49
Show Gist options
  • Save vladi-strilets/ed81634301f8e6221eb71c068b25ca59 to your computer and use it in GitHub Desktop.
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
// 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