React.JS / Next.JS NextAuth `useSession()` latency causes page load with the wrong user session info

140 Views Asked by At

I am using next 14.0.3, react 18.2.0. A page in the application will call different backend service endpoints based on the presence / absence of user session object (whether the user is authenticated). However, there is a small window where the session is undefined during page refresh F5 due to the latency of useSession() from next-auth. This will cause wrong information displayed when the page is ready. Even when using useEffect to track changes in session object it would call the service endpoint twice and will have performance impact.

const { data: session, update } = useSession()

  const getProductsByBrand = async () => {
    const request = new GetProductsRequest()
    request.setBrandid((brandId as string) || '')
    const pageReq = new PageRequest()
    pageReq.setPage(page - 1)
    pageReq.setPagesize(pageSize)
    request.setPaging(pageReq)
    request.setLocale(router.locale || '')
    if (session?.user?.id) 
        request.setUserid(session!.user.id)
    const res = session?.user?.id ? 
    await ProductService.getProducts(request, getMetaData(session?.user?.accessToken)) : 
    await ProductService.getProductsPublic(request, {})
    if (res.getProductsList()?.length > 0) {
// show data
    }
    setLoading(false)
  }

  useEffect(() => {
    setLoading(true)
    getProducts()
  }, [brandId])

How best to tackle this issue?

0

There are 0 best solutions below