Open
Description
Package containing the bug
next-drupal (NPM package)
Describe the bug
Reason: undefined
cannot be serialized as JSON. Please use null
or omit this value.
If you try to use in the next-drupal 2 beta to get the menu tree and add this to the getStaticProps return you will get this error.
I find out that the new class 'DrupalMenuTree' return a false empty value. It return 'undefined' instead of 'null'.
Expected behavior
A clear and concise description of what you expected to happen.
Steps to reproduce:
- use the starter pages package
- try to get menu in the getStaticProps
const { tree, items } = await drupal.getMenu('main');
- then return them
return { props: { menus: { main: tree ?? null, }, resource, }, };
- and you will get this
⨯ N [Error]: Error serializing `.menus.main[0].items[0].items` returned from `getStaticProps` in "/[...slug]". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
Additional context
As workaround I create a copy of the 'DrupalMenuTree' class and only change one line.
import type { DrupalMenuItem, DrupalMenuItemId } from 'next-drupal';
export class DrupalMenuTree<
T extends {
id: DrupalMenuItemId;
parent: DrupalMenuItemId;
items?: T[];
} = DrupalMenuItem,
> extends Array {
parentId: DrupalMenuItemId;
depth: number;
constructor(menuItems: T[], parentId: DrupalMenuItemId = '', depth: number = 1) {
super();
this.parentId = parentId;
this.depth = depth;
if (menuItems?.length) {
this.build(menuItems, parentId);
}
}
build(menuItems: T[], parentId: DrupalMenuItemId) {
// Find the children of the specified parent.
const children = menuItems.filter((menuItem) => menuItem?.parent === parentId);
// Add each child to this Array.
for (const menuItem of children) {
const subtree = new DrupalMenuTree<T>(menuItems, menuItem.id, this.depth + 1);
// Change here the undefined to null
this.push({
...menuItem,
items: subtree.length ? subtree : null,
});
}
}
}
After that I will get the menu and took the items and build a tree with the new class.
return {
props: {
menus: {
main: menu ?? null,
},
resource,
},
};
And it will work