useEffect does not re-run when the params changes

Viewed 5316

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>
    );
}
3 Answers
import { hasIn } from "lodash";

const Headlines = (props) => {

  const [state, setState] = React.useState({ status: "loading", data: [], currentSection: "" });
  const filterList = ["world", "politics", "business", "technology", "sports"];

  useEffect(() => {
    if (hasIn(props, "match.params.section") &&
      filterList.indexOf(props.match.params.section) > -1 &&
      currentSection !== props.match.params.section
    ) {
      
      props.getArticles(props.match.params.section).then((result) => {
        if (result.length > 0) {
          setState({ status: "found", data: result, currentSection: props.match.params.section });
        } else {
          setState({ status: "notfound", data: [], currentSection: "" });
        }
      }).catch((error) => {
        console.log(error);
        setState("notfound")
      })
    } else {
      setState("notfound")
    }
  }, [props]);

  switch (state.status) {
    case "notfound":
      return (
        <Container fluid>
          <h1>The page cannot be found</h1>
        </Container>
      );
    case "found":
      return <Container fluid className={classes.headlines}>
        {data.map((article) => {
          return <HeadlineItem key={article.id} article={article} />
        })}
      </Container>
    default:
      return <Spinner />
  }

};

I have created a simple working version based on your snippets, please have a look at below codesandbox:

A simple working version

What did I do? Basically, from your snippet, eslint has warned me this message:

React Hook useEffect has a missing dependency: 'props'. 
Either include it or remove the dependency array. However, 'props' will change when *any* prop changes, 
so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect. (react-hooks/exhaustive-deps)

You should destructure the section param outside the useEffect first like this:

 const [articles, setArticles] = useState([]);
 const { section } = props.match.params;

 useEffect(() => {
    console.log(section);
    setArticles([`${section} 1`, `${section} 2`]);
  }, [section]);
  if (
    section !== undefined &&
    section !== "world" &&
    section !== "politics" &&
    section !== "business" &&
    section !== "technology" &&
    section !== "sports"
  ) {
    return <span>The page cannot be found</span>;
  }

Code looks fine . I think while giving invalid section param props.getArticles() is breaking it seems .Thats why it is breaking .If you are making http call , add try catch and check .

 props.getArticles(props.match.params.section === 'sports' ? 'sport' : props.match.params.section);
Related