kl_user_333
kl_user_333

Reputation: 143

Next.js SWR accessing data from cache

I have a problem with accessing data from cache. I have my dahboard component. Data fetching here is ok, and i can access it.

const Dashboard = ({ code }) => {
  const { 
    data, 
    error, 
    mutate 
  } = useSWR(['/api/user', code], (url, code) => api.auth.getAuthData({ code }))
  return (
    <MainLayout>
      <div>
        dasdasdasasd
      </div>
    </MainLayout>
  )
}

The problem starts when i'm trying to access this data in other component.

const Navbar = () => {
  const { 
    data, 
    error, 
    mutate 
  } = useSWR(['/api/user'])
  console.log(data)
  return (
    <Styled.Navbar>
      dasdasdas
    </Styled.Navbar>
  )
}

Data in navbar component is undefinied. Any reason why this is not working? Whole app is wrapped into SWR provider.

Upvotes: 0

Views: 1777

Answers (1)

Alexander Lebed
Alexander Lebed

Reputation: 13

You're using 'code' value as a part on the key when fetching the data. To get cached results you need to pass the same key ['/api/user', code]

const { 
        data, 
        error, 
        mutate 
      } = useSWR(['/api/user', code])

Upvotes: 0

Related Questions