-
-
Save brigand/b0532772f064ea4a4b64f221e5175477 to your computer and use it in GitHub Desktop.
react-router - clicking a link again refreshes data
This file contains hidden or 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
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