HughMungus
HughMungus

Reputation: 53

react router, how to make page refresh on url change?

I am making a movie app, where the each movie has its own dedicated page. On this page I have provided similar movies that can be clicked on and ideally would take you to its own movie page. I have a route that looks like this

<Route name="movie" path="/movie/:movieID" exact ><MoviePage /></Route>

the link to this route is in each and every movie component that I have created. The issue is that when I click on a similar movie the url changes to the url of the similar movie and I am able to access the similar movie's properties in the developer console, however the page itself does not change. But once refreshed the page's contents change to those that correspond to the url.

I cannot find a way to force refresh the page in order to get the new movie's information to be displayed.

Upvotes: 5

Views: 6936

Answers (1)

Drew Reese
Drew Reese

Reputation: 203466

The issue is likely that the MoviePage component needs to react to the movieID route param updating.

Given Route:

<Route name="movie" path="/movie/:movieID"  exact>
  <MoviePage />
</Route>

MoviePage:

Use an useEffect hook to handle any logic/data fetching/etc based on the movieID param updating.

const { movieID } = useParams();

React.useEffect(() => {
  // movieID on initial render or subsequent render when updated
  // logic to use movieID and resynchronize any data.
}, [movieID]);

If still using class components, then use the componentDidUpdate lifecycle method. (Assumes MoviePage wrapped in withRouter HOC to receive route props, specifically the match prop)

componentDidUpdate(prevProps, prevState) {
  if (prevProps.match.params.movieID !== this.props.match.params.movieID) {
    // logic to use movieID and resynchronize any data.
  }
}

Upvotes: 4

Related Questions