Help needed: how to check for page first load, to change callback behaviour?

I have a bunch of callbacks (emphasis on plural) that are responsible for printing different plots.

I would like them to act one way when the page is loaded first time, and another way during the rest of the session when fired again.

How can I implement a condition that checks if the page is being loaded the first time?

I tried hiding a flag inside a hidden Div, but obviously I can’t make it work that way, as the flag would be both the input and the output.

Changing the flag internally within a single callback also can’t work, because the other callbacks won’t see that the page is being loaded for the 1st time, given that they happen in parallel.

In pseudo-code, I’m trying to create something that works like this:

def is_first_load():
Return True if page is being loaded the first time,
and changes its value to False AFTER all callbacks ran once.

    if first_load() == True:
        return A
        return B

    if first_load() == True:
        return X
        return Y

Check out the following. If you place the ctx = dash.callback_context at the start of your callback(s), you can use the info it provides to determine your answer (I believe, since I don’t know how your callbacks are invoked after first-page load). I have implemented a helper function to return True or False if the States are not populated (which would be true on first load) or if inputs are None (which is typical on first page load). Hopefully this spawns an idea on how you can use this to satisfy your needs.

# Place this command at the start of each callback
ctx = dash.callback_context

# Show CTX values
print(u''' ctx = {}'''.format(json.dumps({
    'states': ctx.states,
    'triggered': ctx.triggered,
    'inputs': ctx.inputs
    }, indent=2)))

# Determine which dcc component invoked callback
clicked = ctx.triggered[0]['prop_id'].split('.')[0]
print(u'''user pressed = {}'''.format(clicked))

That’s great, thanks for sharing!

Is the callback_context by any change derived from flask? I’m pretty new to dash and totally stranger to flask, so I have little clue about which methods it implements.

Sure think! When I discovered the callback_context it made my code so much cleaner. I’m not 100% sure it’s derivation. You’d have to dive into the source code to find out.

Isn’t there any documentation about it? I couldn’t find anything in the dash docs.

Btw, since Karma is a b***, your solution works, but it turns out that my entire logic is not what I needed to fix the problem I was trying to address. FML

This is all I found: - see FAQ titled “How do I determine which Input has changed?

Drats that it won’t fix your problem…


It’s still good knowledge to have for the community nonetheless, even if it’s not fixing my problem, it will fix someone else’s!

1 Like