How to update datatable inside a function using Callback?

Viewed 173

Hi Guys i try to update the datatable data inside app that initialized from a display() function like this, but the data table is not updated, however if initialized the apps without a display() but write the div inside directly, the data table is updated, is there a way for me to update the datatable data using callback if i declare the div inside a function ?

import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_table as dt
from dash.dependencies import Input, Output
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')

app = dash.Dash(__name__)



states = df.State.unique().tolist()

app.layout = display()

@app.callback(
    Output('table-container', 'data'),
    [Input('filter_dropdown', 'value') ] )
def display_table(state):
    dff = df[df.State==state]
    return dff.to_dict("records")

display()

if __name__ == '__main__':
    app.run_server(debug=True, use_reloader=False)

def display() :
   return html.Div(
    children=[
    dcc.Dropdown(
            id='filter_dropdown',
            options=[{'label':st, 'value':st} for st in states],
            value = states[0]
            ),
    dt.DataTable(id='table-container') ]
    )```
1 Answers

Setting the initial data on layout looks to achieve what you need:

import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_table as dt
from dash.dependencies import Input, Output
import pandas as pd


df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
app = dash.Dash(__name__)

states = df.State.unique().tolist()

@app.callback(Output('table-container', 'data'),
              [Input('filter_dropdown', 'value') ])
def display_table(state):
    dff = df[df.State==state]
    return dff.to_dict("records")


def display() :
   return html.Div(
    children=[
    dcc.Dropdown(
            id='filter_dropdown',
            options=[{'label':st, 'value':st} for st in states],
            value = states[0]
            ),
    dt.DataTable(
        id='table-container',
        columns=[{"name": i, "id": i} for i in df.columns],
        data=df.to_dict('records')
        )]
    )


app.layout = display()


if __name__ == '__main__':
    app.run_server(debug=True, use_reloader=True)

enter image description here

Related