Skip to content

How to use load_data event to populate TreeSelect dynamically? #81

@smlkdev

Description

@smlkdev

Hi,

I'm currently using TreeSelect in ModelScope Studio and I would like to populate its options dynamically using the load_data function. However, I couldn't find clear documentation or examples explaining how to implement this properly.

Specifically, I'm trying to:

  • Fetch tree data asynchronously when the component loads or when a node is expanded.
  • Understand the structure and expected return format for load_data.
import gradio as gr
import modelscope_studio.components.antd as antd
import modelscope_studio.components.base as ms

        with ms.Application():
            with antd.ConfigProvider():
                initial_data = [
                    {"id": 1, "pId": 0, "value": "Company 1", "label": "Company 1"},
                    {"id": 3, "pId": 1, "value": "Doc 1", "label": "Doc 1", "isLeaf": True},
                    {"id": 2, "pId": 0, "value": "Company 2", "label": "Company 2"},
                ]
                tree = antd.TreeSelect(
                    show_search=False,
                    elem_style=dict(width="100%"),
                    dropdown_style=dict(maxHeight=400, overflow="auto"),
                    multiple=False,
                    placeholder="Please Select",
                    tree_checkable=True,
                    show_checked_strategy="SHOW_CHILD",
                    tree_default_expand_all=False,
                    tree_data=initial_data,
                    tree_data_simple_mode=True,
                )

                @tree.tree_expand()
                def tr_ex(evt: gr.EventData):
                    print(f"expand_payload: {evt._data["payload"]}")

                @tree.load_data(outputs=tree)
                def tr_ld(evt: gr.EventData):
                    print(f"loaddata_payload: {evt._data["payload"]}")
                    new_data = initial_data.copy()
                    new_data.append({"id": 4, "pId": 2, "value": "Doc 2", "label": "Doc 2", "isLeaf": True})

                    return gr.update(tree_data=new_data)

Here is the issue I'm facing:

When I open the node "Company 2", I get an error in the browser console. I'm not sure how to properly add child elements dynamically under that node using the load_data function in Python.

Image

I found a working example in Ant Design's documentation using React and TypeScript:

👉 https://stackblitz.com/edit/react-bkaabn4n?file=demo.tsx

It shows how to dynamically load children nodes when a parent is expanded. However, I don’t know how to adapt this logic within the Python context of ModelScope Studio.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions