Using Clientside callback value

I’m attempting to glean the users timezone using a clientside callback. I have a javascript function which places the users current timezone in a hidden div, and then I want to use the state of that in my other Dash callbacks:

import dash, flask
from dash import dcc, html, clientside_callback
from dash.dependencies import Input, Output, State

app = dash.Dash(__name__,title='test')
app.config.suppress_callback_exceptions = True
server = app.server

app.layout = html.Div([dcc.Location(id='page-url'),
						html.Div(id='user_tz',style={'display':'none'}),
						html.Div('This is just a test',id='page-content')])

clientside_callback("""function(id) {
						return Intl.DateTimeFormat().resolvedOptions().timeZone;
					}""",
					Output('user_tz','children'),Input('user_tz','id'))

@app.callback([Output('page-content','children')],
			  [Input('page-url','pathname'),
			  Input('page-url','search')],
			  [State('user_tz','children')])
def display_page(current_pathname,current_search_params,current_user_tz):
	print('Testing Current Timezone:')
	print(current_user_tz)
	return ['This is a test.  Current timezone is {}'.format(current_user_tz)]

From inspection, i can see the value is correctly placed in the div:

<div id="user_tz" style="display: none;">America/Los_Angeles</div>

However, the variable for the timezone in the callback is None, and the output is “This is a test. Current timezone is None”, and I’m not sure exactly why.

1 Like

Hey,
the display_page get fired before the clientside can update the div, when you prevent update and then fire with a button it works.

import dash, flask
from dash import dcc, html, clientside_callback
from dash.dependencies import Input, Output, State

app = dash.Dash(__name__,title='test')
app.config.suppress_callback_exceptions = True
server = app.server

app.layout = html.Div([dcc.Location(id='page-url'),
						html.Div(id='user_tz',style={'display':'none'}),
						html.Div('This is just a test',id='page-content'),
                        html.Button('Display Timezone', id= 'display')])

clientside_callback("""function(id) {
                        const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
                        console.log(tz);
						return tz;
					}""",
					Output('user_tz','children'),Input('user_tz','id'))

@app.callback([Output('page-content','children')],
			  Input('display', 'n_clicks'),
            State('page-url','pathname'),
			  State('page-url','search'),
			  State('user_tz','children'),
                prevent_initial_call = True
)
def display_page(n, current_pathname,current_search_params,current_user_tz):
	print('Testing Current Timezone:')
	print(current_user_tz)
	return ['This is a test.  Current timezone is {}'.format(current_user_tz)]

if __name__ == '__main__':
    app.run_server(debug=True)
1 Like