Black Lives Matter. Please consider donating to Black Girls Code today.

Remember n_clicks of button

I’m trying to update one target with multiple buttons and need a way to figure out which button was fired when a callback gets activated, and preferably would not want the callback to run continuously. This code works in debug but from my overview of Dash it’s my understanding it will break in Production. What’s the right way to accomplish this? Thanks.

import dash
import dash_core_components as dcc
import dash_html_components as html

# In[3]:

app = dash.Dash(__name__)
app.layout = html.Div([
    html.Div(["No Button"], id="innerupdate"),
    html.Div(html.Button("Firstbutton", id="firstbutton")),
    html.Div(html.Button("Secondbutton", id="secondbutton")),
    html.Div(html.Button("Thirdbutton", id="thirdbutton"))]

nfirst = 0
nsecond = 0
nthird = 0

    dash.dependencies.Output("innerupdate", "children"),
    [dash.dependencies.Input("firstbutton", "n_clicks"),
     dash.dependencies.Input("secondbutton", "n_clicks"),
     dash.dependencies.Input("thirdbutton", "n_clicks")]
def fbup(nfclicks, nsclicks, ntclicks):
    global nfirst
    global nsecond
    global nthird
    if nfclicks is not None and nfclicks > nfirst:
        nfirst = nfclicks
        return "First Button"
    if nsclicks is not None and nsclicks > nsecond:
        nsecond = nsclicks
        return "Second Button"
    if ntclicks is not None and ntclicks > nthird:
        nthird = ntclicks
        return "Third Button"
    return "No Button"


Indeed, having global variables is not safe when you have multiple sessions of the app, since one user’s session can affect another user’s session through these variables. Here you could use a dcc.Store ( to store the numbers nfirst, nsecond and nthird.