joe
joe

Reputation: 173

RangeError: Maximum call stack size exceeded NEXTJS

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

Upvotes: 11

Views: 6153

Answers (5)

halo
halo

Reputation: 101

You are trying to send back the whole result of the find, if you are using mongoose (which you do), you can try to add lean() at the end of your query like this:

return await Product.find({}).lean();

That returns plain JavaScript objects instead of full Mongoose documents and it should solve your problem.

Upvotes: 0

Wladimir
Wladimir

Reputation: 36

Even though the answer from Simon Dold works fine, the better solution compatible with typescript would be to map a Sequelize Model instance to JSON serialisible object, like

const user = await User.findOne({where: {id}}).then(user=>({id: user.id, name: user.name}))

Upvotes: 0

Aditya Advani
Aditya Advani

Reputation: 916

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.

Upvotes: 3

Simon Dold
Simon Dold

Reputation: 141

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.

Upvotes: 12

Brian Watroba
Brian Watroba

Reputation: 111

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.

Upvotes: 11

Related Questions