Store Pages in a Variable / dcc.store in order to have a faster multi page app

Hi guys! So my question goes like this:

I have a multi-page app, and till now I have used to create the whole page from scratch each time
my URL changed by calling a function that creates the page.
another way is to store the page in a Global variable and pass the variable content instead of creating everything from scratch, but that creates a problem.

Let’s say I have my app deployed on openshift, the moment the global variable was created the data inside it will NEVER change.
And my goal is to have an app that only updates the data if the user refreshes the page by doing f5 or just opening the app.

I thought about storing the page in a dcc.store, the problem is that well I can’t cause it’s not a dictionary or a string or anything the store accepts, it’s a bunch of HTML elements.

Does anyone have an idea how I can achieve this?

hopefully, I explained everything well if not please do say so I will gladly elaborate the question.

Hi,

As I mentioned to you in private, it is possible to store the page in dcc.Store directly because Dash converts automatically the components into json objects.

Here is a trivial example of a multi-page application where the page updates are made clientside:

from dash import Dash, html, dcc, Input, Output, State, callback, clientside_callback

app = Dash(__name__)

pages_dict = {
    "/": html.Div(
        [
            html.H1("Home!"),
            dcc.Link("Go to Page 1", href="/page1"),
            html.Br(),
            dcc.Link("Go to Page 2", href="/page2"),
        ]
    ),
    "/page1": html.H1("Page 1"),
    "/page2": html.H1("Page 2"),
}

app.layout = html.Div(
    [
        html.Div(id="content"),
        dcc.Store(id="store", data=pages_dict),
        dcc.Location(id="url"),
    ]
)

clientside_callback(
    """
    (pathname, pages) => pages[pathname]
    """,
    Output("content", "children"),
    Input("url", "pathname"),
    State("store", "data"),
)

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

For further reference, note also that a component can be written as a dictionary (or JS object clientside) in the following way:

{
    "namespace": "dash_html_components",
    "type": "Div",
    "props": {
        "id": "example",
        "children": [
            {
                "namespace": "dash_html_components",
                "type": "H1",
                "children": "Hello world!"
            }
        ]
    }
}
1 Like