RangeError: Maximum call stack size exceeded NEXTJS
Asked Answered
C

3

9

I'm still a beginner in Nextjs I get range error when i try to fetch products from database, ihave the same exact code for categories with no problem at all...

this my nextjs server action:

export async function getProducts() {
try {
connectToDB();
return await Product.find({});
} catch (error: any) {
throw new Error(`Failed to catch products : ${error.message}`);
}
}

this is from my client side:

const getAllProducts = async () => {
try {
  const response = await getProducts();
  console.log('response: ', response);
  setProducts(response);
} catch (error) {
  console.log(error);
} useEffect(() => {
getAllProducts()}, []);

can someone tell me whats wrong here i see no loops and i have the same exact code literally for categories section no problems at all

Confessor answered 12/9, 2023 at 8:41 Comment(4)
the useEffect can cause you to infinite loop which throw that errorCamarilla
even if i deleted the useeffect and called getAllproducts function from another function it causes the same errorConfessor
how does the connectToDB looks like?Camarilla
let isConnected = false; export const connectToDB = async () => { mongoose.set("strictQuery", true); if (!process.env.MONGODB_URL) return console.log("Missing MongoDB URL"); if (isConnected) { console.log("MongoDB connection already established"); return; } try { await mongoose.connect(process.env.MONGODB_URL); isConnected = true; console.log("MongoDB connected"); } catch (error) { console.log(error); } };Confessor
B
9

I had a same problem. Nextjs seems to have problems sending your object that you get back from the database to a client component.

A working workaround that helped me was the following:

In the server action stringify your result:

connectToDB();
const products = await Product.find({})
return JSON.stringify(products);

And than at the client side parse the string back to json.

const response = await getProducts();
responseJson = JSON.parse(response)
console.log('response: ', responseJson);

I know this can have several problems since a string is now being sent. But it currently works for me. However, the solution is not perfect and should not always be used.

Barringer answered 24/12, 2023 at 13:45 Comment(0)
G
6

Within Nextjs 13/14, the "Maximum call stack size exceeded" error usually comes from a mismatch between server and client components.

In this case, it seems your server action likely isn't returning a plain object (which is a requirement), and can throw this error.

Another common cause of this error is rendering a server component as a child of a client component.

Groat answered 30/11, 2023 at 14:39 Comment(0)
T
1

In my case I was passing ORM objects directly into the client component, and they were not serializing correctly. After converting them to JSON it worked great, the error went away.

Thoria answered 29/7 at 23:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.