I'm building a small app that pulls stats from the NHL API and displays them. The main aspect of my app is viewing team stats and I have a couple components that send API calls and retrieve the appropriate stats i.e. if the user clicks the NY Rangers link the API call retrieves Rangers stats, if the user clicks the Philadelphia Flyers link the API call retrieves Flyers stats, etc...
A couple different components make API calls and they look like this:
useEffect(() => {
axios.get(`https://statsapi.web.nhl.com/api/v1/teams/${teams[teamName].id}/stats`)
.then(async res => {
setTeamStats(res.data.stats[0].splits[0].stat);
setTeamPlaceInLeague(res.data.stats[1].splits[0].stat);
})
.catch(err => {
console.log('Error retrieving team stats : ' + err);
})
}, []);
As you can see I'm using template literals and plopping in the appropriate endpoint in the
${teams[teamName].id} variable.
I was using a Material-UI template with a side menu for navigation. When the user would navigate from one team's page to another the API call would re-fire i.e. navigating away from the Rangers page by clicking the Flyers link would automatically resend the API call and retrieve the Flyers data. I ditched the Material-UI navigation the template used and built my own. Now when the user navigates from one team's page to another they are sent to the appropriate page but the first team's data is being shown i.e. when the user is on the Rangers' page and clicks the link to go to the Flyers' page they are sent to /flyers like intended, but the Rangers stats are still being shown.
View the app on Netlify, click the hamburger menu, and navigate from one team to another and see what I mean. React-router navigates to the appropriate page, but the data from the previous page is loaded.
How can I force useEffect to resend the axios call when the user navigates to a different team's page? Is this a matter of using something like componentDidUpdate in order to re-render the component? I'm new to Hooks and not sure how that would work with react-router.