'Passing a value from a page to another in dash plotly

I have two pages in dash plotly, and an index file who run the pages :

  • Index.py
  • Page 1
  • Page 2

I have a variable in page 1 which I want to pass it in page 2 and work with it. ( example of code) Is it possible in Dash plotly ? I saw somewhere that I can use Dcc.store, but how can I stock this variable in it ?

First_page = html.Div([
html.Div([dcc.Input(id='date_start', type='text', value='2021')]),
...
...
])

@app.callback(
    Output('someoutput', 'children'),
    [Input('someinput', 'value')])

#Uploading a certain table
@app.callback(
    Output('datatable', 'data'),
    Input('someinput', 'value'))

def function(somedata):
    #Get the VARIABLE
...
...
    variable= 12 (result of the operation in funtion)

How can I get the VARIABLE value (12) and inject it in page 2 please ?

Second_page = html.Div([
html.Div([dcc.Input(id='', type='text', value='')]),
...
...
])

@app.callback ()

def function_page2(somedata_page2):
    #Work with the VARIABLE in first page
...

Thank you .



Solution 1:[1]

You can store the variable (assuming it is not too large) using dcc.Store that can be accessed by any callback. I've given an elaborate example here using dataframes, but the idea is essentially the same for other datatypes.

For integers or strings, it's much simpler in that you have a callback to store the information you want in dcc.Store, then in other callbacks that you wish to access that value, you simply input the data attribute of the store and you'll receive it as is. Here's a generic example of how you can pass an integer between callbacks:

import dash_bootstrap_components as dbc
import dash
from dash import html, Input, Output, dcc, State

app = dash.Dash(
    external_stylesheets=[dbc.themes.BOOTSTRAP]
)

app.layout = html.Div([
    dcc.Store(id="store-data"),
    dbc.Button("Load Store", type="submit", id="load-btn"),
    dbc.Button("Get from Store", type="submit", id="get-btn"),
    html.Div(id="output-store-data")
])


@app.callback(
    [
        Output('store-data', 'data'),
    ],
    [
        Input('load-btn', 'n_clicks'),
    ],
    prevent_initial_call=True,
)
def load_store(_):
    var = 12
    return [var]


@app.callback(
    [
        Output("output-store-data", "children"),
    ],
    [
        Input("get-btn", "n_clicks"),
    ],
    [
        State('store-data', 'data'),
    ],
    prevent_initial_call=True,
)
def get_from_store(_, var_store):
    return [var_store]


if __name__ == "__main__":
    app.run_server()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Al Mouiee