Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

flatDataToTree doesn't work in a NextJS server component #17

Open
donalffons opened this issue Feb 19, 2024 · 0 comments
Open

flatDataToTree doesn't work in a NextJS server component #17

donalffons opened this issue Feb 19, 2024 · 0 comments

Comments

@donalffons
Copy link

This simple demo

import { client } from "@/sanity/lib/client";
import { groq } from "next-sanity";
import { flatDataToTree } from "@sanity/hierarchical-document-list";

export default async function Page() {
  const pageHierarchy = await client.fetch(groq`*[_id == "page-hierarchy"][0] {
    tree[] {
      // Make sure you include each item's _key and parent
      _key,
      parent,
      value {
        reference->{
          title,
          slug,
          content,
        }
      }
    }
  }`);
  const pageTree = flatDataToTree(pageHierarchy.tree);
  return (
    <div>
      {JSON.stringify(pageTree, null, 2)}
    </div>
  );
}

doesn't work as a NextJS server component. Error message

TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component

The root cause is in the @nosferatu500/react-sortable-tree => react-dnd@14 dependency, which probably exposes some react-context related functionality.

I fixed it by including this code in my repository:

// /sanity/lib/flatDataToTree.ts
import { SanityReference } from "next-sanity";

export interface StoredTreeItem {
  _key: string;
  _type: string;
  value?: {
    _type: string;
    reference?: SanityReference;
    docType?: string;
  };
  parent?: string | null;
}

interface TreeItemWithChildren extends StoredTreeItem {
  children?: TreeItemWithChildren[];
};

const getTreeFromFlatData = ({
  flatData,
  getKey = (node) => node.id,
  getParentKey = (node) => node.parentId,
  rootKey = '0',
}: {
  flatData: any
  getKey: (node: any) => string
  getParentKey: (node: any) => string
  rootKey: string | null
}) => {
  if (!flatData) {
    return []
  }

  const childrenToParents: Record<string, string[]> = {}
  for (const child of flatData) {
    const parentKey = getParentKey(child)

    if (parentKey in childrenToParents) {
      childrenToParents[parentKey].push(child)
    } else {
      childrenToParents[parentKey] = [child]
    }
  }

  if (!(rootKey! in childrenToParents)) {
    return []
  }

  const trav: (parent: any) => any = parent => {
    const parentKey = getKey(parent)
    if (parentKey in childrenToParents) {
      return {
        ...parent,
        children: childrenToParents[parentKey].map((child) => trav(child)),
      }
    }

    return { ...parent }
  }

  return childrenToParents[rootKey!].map((child) => trav(child))
}

export default function flatDataToTree(data: StoredTreeItem[]): TreeItemWithChildren[] {
  return getTreeFromFlatData({
    flatData: data.map((item) => ({
      ...item,
      parent: item.parent || null,
    })),
    getKey: (item) => item._key,
    getParentKey: (item) => item.parent,
    rootKey: null as any,
  }) as TreeItemWithChildren[];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant