'use client'
import { LayoutProps } from '@/lib/types/layout'
import { isServer, QueryClient, QueryClientProvider } from '@tanstack/react-query'
import queryClient from '@/api/config/query-client'

let browserQueryClient: QueryClient | undefined = undefined

function getQueryClient() {
  // Server: always make a new query client
  if (isServer) return queryClient

  // Browser: make a new query client if we don't already have one
  // This is very important, so we don't re-make a new client if React
  // suspends during the initial render. This may not be needed if we
  // have a suspense boundary BELOW the creation of the query client
  if (!browserQueryClient) browserQueryClient = queryClient
  return browserQueryClient
}

export default ReactQueryProvider
export function ReactQueryProvider({ children }: LayoutProps) {
  // NOTE: Avoid useState when initializing the query client if you don't
  //       have a suspense boundary between this and the code that may
  //       suspend because React will throw away the client on the initial
  //       render if it suspends and there is no boundary
  return <QueryClientProvider client={getQueryClient()}>{children}</QueryClientProvider>
}
