django-unicorn
django-unicorn copied to clipboard
Update component state on browser forward/backward navigation on history
Hello, my question is, if it would be possible that the state (and rendering) of a component is updated when the user navigates through his browser history. I have used LocationUpdate to "store" variables within the browser URL and I expect the component to display as it was before, when I click the "back"-Button of the browser. As investigated in #422 the URL changes correctly, but the pages content stays the same and does not update accordingly. From my point of view, that is not working as expected.
I read this thread and came to a workaround by adding an JS event listener and calling an action method of my component that parses the manually transmitted url of the history and sets the components variables to their previous values (as defined in the history's URL):
<!-- component template -->
<script>
window.addEventListener('popstate', function () {
Unicorn.call('{{ unicorn.component_name }}', "refresh_on_history_change", window.location.search)
});
</script>
# in component view
def refresh_on_history_change(self, query_string: str):
query_string = query_string[1:] if query_string.startswith('?') else query_string
context = MyComponentContext.url_decode(query_string)
self._init_context_of_component(context=context)
I am pretty sure, that there might be a more general and nicer way to integrate it into your code.
Yeah, this does not seem optimal. I will take a look to see if there is a better approach.
I have the same problem. Fix would be greate!
When using the fix from @pa-hqt it would be nice to trigger the loading state from javascript can not find anything about that in the docs.