Skip to content

Error serializing .menus.main[0].items[0].items returned from getStaticProps #793

Open
@taskrider2022

Description

@taskrider2022

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:

  1. use the starter pages package
  2. try to get menu in the getStaticProps
  3. const { tree, items } = await drupal.getMenu('main');
  4. then return them
  5. return { props: { menus: { main: tree ?? null, }, resource, }, };
  6. and you will get this
  7. ⨯ 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtriageA new issue that needs triage

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions