Hi,
I’m trying to figure out why the sidebar state is being lost on one specific page of my app.
The app has a collapsible sidebar whose state (open/closed) is stored in localStorage
. A CSS transition is used to animate the opening/closing of the sidebar. I’m using Hotwire to manage the UI state, and the sidebar’s state is successfully preserved across most pages—except for one.
On this problematic page, when the page loads, the sidebar replays its opening animation, suggesting the element state is lost when this page is opened. Below is the Stimulus controller handling the sidebar behavior:
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "sidebar", "openSidebarBtn" ]
static values = { isOpened: Boolean }
connect() {
const sidebarState = localStorage.getItem('sidebarState')
console.log(this.element)
console.log('sidebarState', sidebarState, 'isOpenedValue', this.isOpenedValue)
this.isOpenedValue = sidebarState;
this.connected = true;
}
disconnect() {
localStorage.setItem('sidebarState', this.isOpenedValue)
}
toggle(event) {
console.log('toggle')
event.preventDefault()
this.isOpenedValue = !this.isOpenedValue
}
isOpenedValueChanged() {
if (!this.connected) return;
console.log('isOpenedValueChanged', this.isOpenedValue)
if (this.isOpenedValue) {
this.open()
} else {
this.close()
}
}
open() {
this.sidebarTarget.classList.remove("-translate-x-full")
this.sidebarTarget.classList.remove("absolute")
this.sidebarTarget.classList.add("translate-x-0")
this.sidebarTarget.classList.add("static")
this.openSidebarBtnTarget.classList.add("hidden")
}
close() {
this.sidebarTarget.classList.remove("translate-x-0")
this.sidebarTarget.classList.remove("static")
this.sidebarTarget.classList.add("-translate-x-full")
this.sidebarTarget.classList.add("absolute")
this.openSidebarBtnTarget.classList.remove("hidden")
}
}
I out of ideas on how to find out what is special about this page/controller.
Any help is much appreciated.
Thanks