I had trouble with this approach. I have a multiple page app that is trying to use the shared data to build the list of options dynamically.
- Defined the functions to convert list to string and vice versa. To keep it the same way as the document specified, they are converted via dataframe.
def to_jsonstr(my_list):
df = pd.DataFrame(my_list)
print("convert list to string")
print(df)
jsonStr = df.to_json(orient='split')
print('jsonStr is {}'.format(type(jsonStr)))
return jsonStr
def from_jsonstr(jsonList):
print("convert dataframe to list")
print('jsonList is {}'.format(type(jsonList)))
df = pd.read_json(jsonList, orient='split')
print(df)
my_list = df[0].values.tolist()
print(my_list)
return my_list
- Two callbacks are added. add_watchlist is called when “add to watch list” button is triggered, which add the new symbol to the existing list. update_dropdown is called when the “intermediate” new-watchlist" string is updated.
app = dash.Dash()
app.config.suppress_callback_exceptions = True
app.layout = html.Div(children=[
# global hidden value
html.Div(id='new-watchlist'),
html.H1(children="My Stock App"),
dcc.Location(id='url', refresh=False),
html.Div(id='page-content')
])
# Add Ticker to New watchlist when add button is clicked
@app.callback(Output('new-watchlist', 'children'),
[Input('add-button', 'n_clicks')],
[State('ticker-input', 'value'),
State('new-watchlist', 'children')]
)
def add_watchlist(n_clicks, ticker, jsonWatchList):
print('json Watchlist is ')
print(jsonWatchList)
# watchList = ['AMZN', 'GOOG', 'TSLA']
# print(watchList)
if(jsonWatchList is None):
watchList = ['AMZN', 'GOOG', 'TSLA']
else:
watchList = from_jsonstr(jsonWatchList)
print('watchList after json loads')
print(watchList)
if ticker is not None and ticker not in watchList:
watchList.append(ticker)
print("after add")
print(watchList)
outJson = to_jsonstr(watchList)
print("outJson is")
print(outJson)
return outJson
# Update Options in dropdown-watchlist
@app.callback(Output('dropdown-watchlist', 'options'),
[Input('new-watchlist', 'children')]
)
def update_dropdown(jsonWatchList):
watchList = from_jsonstr(jsonWatchList)
print("in update_dropdown")
print(watchList)
return [{'label': i, 'value': i} for i in watchList]
I got stuck in the callback function update_dropdown was only triggered once during page load, but not when the list is changed (I can see from the view that new-watchlist is updated, but the callback is not triggered). Could someone please help?
new-watchlist is updated now to {“columns”:[0],“index”:[0,1,2,3],“data”:[[“AMZN”],[“GOOG”],[“TSLA”],[“C”]]}
but update_dropdown callback was not triggered by this change.
A more detailed log of things I’ve tried so far