Next.js Discord

Discord Forum

How can I fetch a JSON once and use it for many components?

Unanswered
Saltwater Crocodile posted this in #help-forum
Open in Discord
Saltwater CrocodileOP
I'm creating an app that allow the user login, then, if this is successfully returns me the user's id, The app saves the user's id into a cookie for later do a fetch to get the user data.... The user data many components will use it, so is stupid do a fetch every time that I need, I thought use a context but I want to know if there are others options.

6 Replies

Saltwater CrocodileOP
Okkok, I will use context, thanks
Saltwater CrocodileOP
I have a question
  const _id = request.cookies.get('_id')?.value
  const user = await findUserById(_id)
  const status = user.status

  for (const route of PRIVATE_ROUTES) {
    if (request.nextUrl.pathname.startsWith(route)) {
      if (status !== 200) {
        return NextResponse.redirect(new URL('/sign-in', request.url))
      }
    }
  }

  if (request.nextUrl.pathname.startsWith('/sign-in')) {
    if (status === 200) {
      return NextResponse.redirect(new URL('/home', request.url))
    }
}
Here I do a fetch for get the user data and control if this exist, I still need use context? Or I have other option with this fetch?
you can use react cache to only need to compute something once per request (it works in server components/server things like route handler)
it won't leak into other requests so its pretty safe