Server Components can only receive plain objects and select built-ins from Client Components. Any classes or null prototypes will not be compatible

I am encountering an error when wrapping the App.ts with queryclientprovider: "Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported." Below is the code snippet from App.ts:





 import Image from 'next/image'
import { Button } from '@/components/ui/button'
import { UserButton,auth } from '@clerk/nextjs'
import Link from 'next/link';
import {LogIn } from 'lucide-react';
import FileUpload from '@/components/FileUpload';
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";



export default async function Home() {

  const queryClient = new QueryClient();
  const {userId}=await auth();
  const isAuth=!!userId
  return (
    <QueryClientProvider client={queryClient}>
    <div className='w-screen min-h-screen bg-gradient-to-b from-black via-black to-sky-900'>
      <div className='absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white'>
         <div className="flex flex-col items-center text-center">
          <div className="flex items-center"> 
          <h1 className='mr-3 text-5xl font-bold-sans md:font-serif  bg-clip-text text-transparent bg-gradient-to-r from-white to-gray-400 '>Chat With Any PDF</h1>
          <UserButton afterSignOutUrl='/'/>
          </div>
          <div className="flex mt-2">
            {isAuth &&
          <Button className=' mb-2 bg-gradient-to-r  from-black via-black to-sky-900 border-2 border-gray-300 border-r-2  hover:bg-gradient-to-l  hover:transition hover:duration-300   '>Go to Chats</Button>}
          </div>
          <p className='  mt-1   md:font-serif  bg-clip-text text-transparent bg-gradient-to-r from-white to-gray-400 '>Script.Ai is a cutting-edge web application designed to streamline your PDF interactions. Simply upload your documents and effortlessly extract answers to your questions, harnessing the power of advanced AI technology for precision and efficiency.</p>
          <div className='w-full mt-4'>
          
   
            {isAuth ? (<FileUpload/>):<Link href={'/sign-in'} >
          

            <Button  className=' bg-gradient-to-r from-black via-black to-sky-900  text-gray-300 border-2 border-gray-300  hover:bg-gradient-to-l  hover:transition hover:duration-300 hover:ease-in-out'>Login to get Started
            <LogIn className='w-4 h-4 ml-2 '/></Button>
            </Link> }
          </div>
          
         </div>
      </div>
    </div>
  </QueryClientProvider>
  )
}




and the code of FileUpload.ts, where I used queryclient due to the use of "useMutation":

"use client";
import { uploadToS3 } from "@/lib/s3";
import { useMutation } from "@tanstack/react-query";
import { Inbox, Loader2 } from "lucide-react";
import React from "react";
import { useDropzone } from "react-dropzone";
import axios from "axios";
import { toast } from "react-hot-toast";
import { useRouter } from "next/navigation";

// https://github.com/aws/aws-sdk-js-v3/issues/4126

const FileUpload = () => {
  const router = useRouter();
  const [uploading, setUploading] = React.useState(false);
  const { mutate, isPending } = useMutation({
    mutationFn: async ({
      file_key,
      file_name,
    }: {
      file_key: string;
      file_name: string;
    }) => {
      const response = await axios.post("/api/create-chat", {
        file_key,
        file_name,
      });
      return response.data;
    },
  });

  const { getRootProps, getInputProps } = useDropzone({
    accept: { "application/pdf": [".pdf"] },
    maxFiles: 1,
    onDrop: async (acceptedFiles) => {
      const file = acceptedFiles[0];
      if (file.size > 10 * 1024 * 1024) {
        // bigger than 10mb!
        toast.error("File too large");
        return;
      }

      try {
        setUploading(true);
        const data = await uploadToS3(file);
        console.log("meow", data);
        if (!data?.file_key || !data.file_name) {
          toast.error("Something went wrong");
          return;
        }
        mutate(data, {
          onSuccess: ({ chat_id }) => {
            toast.success("Chat created!");
            router.push(`/chat/${chat_id}`);
          },
          onError: (err) => {
            toast.error("Error creating chat");
            console.error(err);
          },
        });
      } catch (error) {
        console.log(error);
      } finally {
        setUploading(false);
      }
    },
  });
  return (
    <div className="p-2 bg-white rounded-xl">
      <div
        {...getRootProps({
          className:
            "border-dashed border-2 rounded-xl cursor-pointer bg-gray-50 py-8 flex justify-center items-center flex-col",
        })}
      >
        <input {...getInputProps()} />
        {uploading || isPending ? (
          <>
            {/* loading state */}
            <Loader2 className="h-10 w-10 text-blue-500 animate-spin" />
            <p className="mt-2 text-sm text-slate-400">
              Spilling Tea to GPT...
            </p>
          </>
        ) : (
          <>
            <Inbox className="w-10 h-10 text-blue-500" />
            <p className="mt-2 text-sm text-slate-400">Drop PDF Here</p>
          </>
        )}
      </div>
    </div>
  );
};

export default FileUpload;

I need assistance in resolving this error.

Answer №1

It appears that you are utilizing next js 14. In order to integrate nextjs14 with react-query, it is necessary to wrap your QueryClientProvider within a client component:

"use client"

import { useState } from 'react';
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const Provider = ({ children }) => {
    const [client] = useState(new QueryClient());

    return <QueryClientProvider client={client}>{children}</QueryClientProvider>
} 

In-App.ts file:


export default async function Home() {
  return (
     <Provider>
        ....
     </Provider>
  )
}

Cause:

Next JS 14 does not support the direct use of provider and context within a server render component since these components are simply HTML streamed in response. By using a client component, you can easily create a client provider.

For more information: refer to this article

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop the print dialog box from causing the page to refresh

I have implemented a print button for an invoice: </script> <!--Function for printing invoice--> <script> function printpage() { window.print() } </script> <button id="print" name="print" class="btn btn-info" onClick="pri ...

Retrieve information from a sensor within an Express server and display it on the user interface

Looking for suggestions on resolving a challenge: I have a Node.js module that retrieves data from a sensor, and I am interested in incorporating a UI element to showcase the sensor data (either in real-time or pseudo-realtime). Is there a way to establ ...

What is the best way to search for a specific value in the Record definition?

In the documentation for Typescript, a type is defined to be used as keys into a Record<>. It seems like this is done to restrict and secure the keys that can be utilized. type CatName = "miffy" | "boris" | "mordred"; W ...

gulp-webpack is unable to locate node packages

Currently working on developing a modern Angular application. I have opted to use gulp-webpack for quick development builds. To handle my TypeScript bundling and node modules dependencies, I am relying on webpack. However, it seems that gulp-webpack is no ...

Customizing the styling of buttons in Highcharts is disabled when in full screen mode

I've integrated highcharts into my Angular application and included a custom button inside the chart to navigate users to another page. However, I encountered an issue when trying to fullscreen the chart using the export menu. The position of the cus ...

Ensure that the form is submitted only after confirming it in the modal with react-hook-form

**I am facing an issue with submitting react-hook-form on confirm in a modal component. Whenever the user selects confirm, I need the form to be submitted directly. I have tried writing the modal inside FormSubmitButton. Also, I have tried placing it insi ...

Simultaneously, two identical messages arrived in the form of push notifications via FCM

I have been working on implementing WebPush notifications using Vue.js and FCM. However, when testing the functionality, I am facing an issue where instead of receiving just one notification from Firebase, TWO IDENTICAL PUSH NOTIFICATIONS are being receive ...

The AJAX session is triggered twice, without displaying an alert the second time

Upon loading the page, an AJAX session is triggered and then again after clicking. Strangely, the readystate change is not happening the second time around. To troubleshoot, I added an alert box in the function which appears during page load but not on cli ...

Navigating through each segment

I'm currently working on a website with sections that are set to be 100% height of the window, but at least 800px tall. My goal is to implement a smooth scrolling functionality where one scroll moves the view from section to section. However, if the ...

Using Ajax to implement a content slider with lightSlider

Seeking assistance in developing a dynamic content slider utilizing the LightSlider plugin. Currently, I have a script that fetches content from a database table (outputting JSON to HTML) and displays 6 div's of content per slide. However, I aim to di ...

Is there a solution available for the error message that reads: "TypeError: Cannot set value to a read-only property 'map' of object '#<QueryCursor>'"?

Everything was running smoothly in my local environment, but once I deployed it on a Digital Ocean Kubernetes server, an error popped up. Any assistance would be greatly appreciated. https://i.stack.imgur.com/VxIXr.png ...

The website encountered an error in loading with the error message "ENOTFOUND" in Cypress

All my cypress tests were running smoothly until one day they all failed to visit the target site. The error message that I received was: cy.visit() failed trying to load: https://mywebsite.com/accounts/login/ We attempted to make an http request to this ...

Node.js seems to be having trouble with emitting events and catching them

I'm having trouble troubleshooting my code. // emitter.js var EventEmitter = require('events').EventEmitter; var util = require('util'); function Loadfun(param1, param2, db){ function __error(error, row){ if(error){ ...

openssl reported an Error Stack error with code 03000086, specifically stating that there was an issue with the initialization

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'digital envelope routines', reason: 'unsupported', code: 'ERR_OSSL_EVP_UNSUPPORTED' } Node.js v19.5.0 I e ...

Understanding TypeScript's ability to infer types in generics

Exploring the world of TypeScript through a robustly typed system for REST requests. Let's dive into the code: This type is used to establish the connection between routes and their respective object types: export interface RoutesMapping { api1: ...

How do you go about making a prop optional in Typescript based on a generic type?

In my app, I have a specific type with optional props based on a generic type: type MyCustomType<R extends Record<string, string> | undefined, A extends string[] | undefined> = { record: R, array: A } There is a function that directly uses ...

Tips for utilizing a printer to print HTML content in PHP

I've stored HTML content in a variable as shown below: $message ="<div> <table align='center'> <tr><td><h1>Tipo de Documentos Report</h1></td></tr> <tr><td>< ...

Error: Material-UI prop type validation failed - Please specify either `children`, `image`, `src`, or `component` prop

Despite having an image prop in CardMedia, I kept encountering this error. Here is a snippet of the code: Error description: const Post = ({ post, setter }) => { const classes = useStyles(); return( <Card className={classes.card} ...

What is the method for including as: :json in your code?

I have a file with the extension .ts, which is part of a Ruby on Rails application. The code in this file looks something like this: export const create = async (params: CreateRequest): Promise<XYZ> => { const response = await request<XYZ> ...

Utilizing the CSS 'overflow: hidden' property and jQuery to restrict users from scrolling during a loading page

OBJECTIVE I aim to restrict the user from scrolling while the page is loading. ISSUE The snippet of code provided successfully prevents the user from scrolling during the additional 2 seconds of the loader animation: $('body').toggleClass(&ap ...