I have 6 links (home, world, politics, business, technology, sports) on my navbar, and I only want the "section" param to be one of these values. If other value of "section" is entered, it will show a "page cannot be found" message.
All 6 links are working correctly. useEffect reruns when another link on the navbar is clicked. However, if I enter an invalid section param, it first shows the "page cannot be found" message, then I click a link on the navbar, useEffect does not rerun and the app crashed.
I cannot figure out why useEffect does not rerun, I did specify the props.match.params.section as its dependency.
const Headlines = (props) => {
useEffect(() => {
console.log(props.match.params.section);
props.getArticles(props.match.params.section === 'sports' ? 'sport' : props.match.params.section);
}, [props.match.params.section]);
if (props.match.params.section !== undefined &&
props.match.params.section !== 'world' &&
props.match.params.section !== 'politics' &&
props.match.params.section !== 'business' &&
props.match.params.section !== 'technology' &&
props.match.params.section !== 'sports') {
return (
<Container fluid>
<h1>The page cannot be found</h1>
</Container>
);
}
return (
props.news.loading ?
<Spinner/>
:
<Container fluid className={classes.headlines}>
{props.news.articles.map((article) => {
return <HeadlineItem key={article.id} article={article}/>
})}
</Container>
)
};
The code of the navbar:
<Nav className="mr-auto">
<NavLink to="/"
exact
className={classes.link}
activeClassName={classes.selected}>Home</NavLink>
<NavLink to="/world"
className={classes.link}
activeClassName={classes.selected}>World</NavLink>
<NavLink to="/politics"
className={classes.link}
activeClassName={classes.selected}>Politics</NavLink>
<NavLink to="business"
className={classes.link}
activeClassName={classes.selected}>Business</NavLink>
<NavLink to="/technology"
className={classes.link}
activeClassName={classes.selected}>Technology</NavLink>
<NavLink to="/sports"
className={classes.link}
activeClassName={classes.selected}>Sports</NavLink>
</Nav>
The code of App.js:
function App() {
return (
<Provider store={store}>
<Router>
<NavigationBar/>
<Switch>
<Route exact path="/:section?" component={Headlines}/>
</Switch>
</Router>
</Provider>
);
}