I am using the built in Multi-Page feature use_pages=True which was added in 2.5 I believe. In my application I would like to trigger a callback when a specific page loads. However, since there are multiple entry points to this page (from other pages as well), I would like to trigger a callback when the URL changes to a specific path (e.g., /home). Is there any way to do this with the built-in multi-page feature??
Any suggestions would be greatly appreciated. Thanks in advance!
You can always include dcc.Location in your layout and trigger your callback with pathname property. Syntax for the input will be same as described in https://dash.plotly.com/urls for Multi-Page Apps without Pages.
Also, if you are using dash>=2.9.2, be sure to use dcc.Location(refresh="callback-nav") so it will navigate without refreshing the page. More info here:
Another tip is to put the dcc.Location in the app.layout above the dash.page_container - then the forward/back browser buttons will work.
I added a dcc.Location at the top of my app.layout and added the refresh='callback-nav' like you recommended. This works great with a callback of the structure @bgivens33 outlined above.
I have an add on to this question. What is the best practice for updating / managing the dcc.Location with various URL query values on a page load? Each time I have tried the single dcc.Location approach, it triggers a circular callback error like so:
User navigates to page causing dcc.Location change
Page load callback fires and sets up the page with query values in the URL string, e.g. /mypage?foo=1
URL is updated with new query values, including some page default values, e.g. /mypage?foo=1&bar=2
Step 1 is triggered again
My only workaround is to have a dcc.Location per page and to the others commenters point, yes it is a mess but I have not found a better way.
I’m not sure what the problem is. Could you make a minimal example that replicates the issue? I have several examples of of updating the URL and using query strings here: