0

I have a list of scores that I am loading using vercel SWR. In my setup im using the same component to render scores but depending on the users route the scores should be updated.

Routing:

/scores /scores/soccer /scores/basketball

Scores.tsx

export function Scores() {
    const address = `api/scores`

    const fetcher = async (url: string) => {
        const response = await axios.get(
            url,
        )
        return response.data
    }

    const { data, mutate } = useSWR(address, fetcher, {
        fallbackData,
        revalidateOnFocus: true,
        revalidateOnReconnect: true,
        refreshInterval: 300000,
        shouldRetryOnError: false,
        revalidateOnMount: true,
    })


    return <div>{data.map((score) => <ScoreComponent score={score} />}</div>
}

Problem

When the page loads everything works as expected. When I click on a next/link to change the route I can see the router change but the data doesnt change. I tried using window.location to change the route and the data changes as expected.

I tried using mutate while listening to the router path change but that didnt work.

    useEffect(() => {
        mutate()
    }, [router.asPath])

Anybody know the correct way to reload SWR data when changing routes?

Jason McFarlane
  • 2,048
  • 3
  • 18
  • 30
  • Why are you expecting the data to change if the request you make to `/api/scores` is exactly the same? How would the data returned be different based on the page? – juliomalves Jun 21 '22 at 22:34

1 Answers1

0

SWR will fetch the data if there is key change or via mutate function. Depending on your case, I think there are two possible approach:

  1. NextJS router events here
useEffect(() => {
  const handleRouteChange = (url, { shallow }) => {
    // SWR mutate function
    mutate()
  }

  router.events.on('routeChangeStart', handleRouteChange)
  return () => {
    router.events.off('routeChangeStart', handleRouteChange)
  }
}, [])
  1. Use different nextjs router path as the SWR key
const address = router.asPath
const { data, mutate } = useSWR(address, fetcher, {
Ahnaf A
  • 1
  • 1