Skip to content

Instantly share code, notes, and snippets.

@brigand
Last active April 11, 2019 17:18
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 brigand/b0532772f064ea4a4b64f221e5175477 to your computer and use it in GitHub Desktop.
Save brigand/b0532772f064ea4a4b64f221e5175477 to your computer and use it in GitHub Desktop.
react-router - clicking a link again refreshes data
import useReactRouter from 'use-react-router';
function UserPage({ match }) {
const [user, setUser] = React.useState(null);
const { history } = useReactRouter();
// If on /user/123 and you click a link to /user/123, history.length will be
// increased by 1, causing the effect to run again
React.useEffect(() => {
let cancel = false;
setUser(null);
getUser(match.params.id)
.then((user) => {
// Only update with the latest request data
if (cancel) { return; }
setUser(user);
});
return () => { cancel = true; };
}, [history.length, match.params.id]);
return <div>{user ? user.name : 'Loading..'}</div>;
}
// in routes...
<Route path="/user/:id" component={UserPage} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment