How to refresh data when using React Router <Link>

Adam C.
Adam C.
Feb 26, 2018 · 2 min read
Diagram credit: https://rangle.github.io/react-training/
<Link to="/">Home</Link>
<Link to={{ pathname: '/', state: 'flushDeal' }}>
Home
</Link>
// set default state of isFlushed = false, which means it's ready for data flushing
constructor(props) {
super(props);
this.state = {
isFlushed: false
};
}
componentWillReceiveProps(nextProps) {
// check current props and nextPros of dealLoaded flag. If dealLoaded was false, and is true, which means the data is fetched, then we should reset isFlushed
if (!this.props.dealLoaded && nextProps.dealLoaded) {
this.setState({
isFlushed: false
});
}
// since we assigned the location.state in <Link>, if we see this prop, and the data is not flushed yet, then flush data, in this case we call loadDeals(), which is a redux action
if (!this.state.isFlushed && nextProps.location.state === 'flushDeal')) {
this.setState({
isFlushed: true,
}, () => this.props.loadDeals());
}
}

Adam C.

Written by

Adam C.

Founder of Shopecific

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade