RangeError: Maximum call stack size exceeded NEXTJS

1.9k views Asked by At

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

2

There are 2 answers

0
Brian Watroba On

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.

0
Simon Dold On

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.