Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[tree view][docs] Example for useTreeViewApiRef with generic type #19426

@caillou

Description

@caillou

Related page

https://mui.com/x/api/tree-view/simple-tree-view/#simple-tree-view-prop-apiRef

Kind of issue

Missing information

Issue description

I am trying to use useTreeViewApiRef to get back the treeItems.

export interface ExplorerNode {
  id: string;
  text: string;
  children?: ExplorerNode[];
  count?: number;
  hasFolders: boolean;
}

const Component = ({ 
  items, 
  onItemsChange 
}: { 
  items: ExplorerNode[]; 
  onItemsChange: (newItems: ExplorerNode[]) => void
}) => {
  const treeApiRef = useTreeViewApiRef();

  return (
    <RichTreeViewPro
      apiRef={treeApiRef}
      items={items}
      onExpandedItemsChange={(_, expandedItems) => {
        const newItems = treeApiRef.current?.getItemTree() || [];
        //    ^ newItems is of type TreeViewBaseItem[]
        onItemsChange(newItems) 
        //            ^ TS Error:
        //              Argument of type 'TreeViewBaseItem[]' 
        //              is not assignable to parameter of type 'ExplorerNode[]'.
      }}
      dataSource={
        {
          // lazy load code
        }
      }
    />
  );
};

With the code as is treeApiRef.current?.getItemTree() returns TreeViewBaseItem[].

I see that useTreeViewApiRef is a generic type. But I fail to see what I need to pass this generic, so that the the items returned from getItemTree() are of type ExplorerNode[].

Is this possible? If so, could we add a dedicated page for useTreeViewApiRef that documents the generic? I really have a hard time parsing the actual type of it:

export type TreeViewAnyPluginSignature = {
  state: any;
  instance: any;
  params: any;
  paramsWithDefaults: any;
  dependencies: any;
  optionalDependencies: any;
  events: any;
  publicAPI: any;
};

export declare const useTreeViewApiRef: <
  TSignatures extends readonly TreeViewAnyPluginSignature[] = RichTreeViewPluginSignatures
>() => React.RefObject<TreeViewPublicAPI<TSignatures> | undefined>;

Context

No response

Search keywords: useTreeViewApiRef typescrip generic

Metadata

Metadata

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions