Where to use JS to update CSS variables
Hi! I'm using CSS variables to set my tailwind colors dynamically - I'm fetching the colors from the API and updating the CSS variables with the values I get back. I'm currently storing the values I get back in a persisted Pinia store, however, the CSS variables get set back to default after refreshing/leaving the page, so I need to run
document.documentElement.style.setProperty('--my-color-var', valueFromApi)
when that happens.
Would it be correct to run this setProperty inside a middleware? Or is there a better way to do this?3 Replies
I would suggest to use pinia-plugin-persistedstate (https://github.com/prazdevs/pinia-plugin-persistedstate) and implement you logic in the afterRestore method.
GitHub
GitHub - prazdevs/pinia-plugin-persistedstate: 🍍 Configurable persi...
🍍 Configurable persistence and rehydration of Pinia stores. - prazdevs/pinia-plugin-persistedstate
hey, sorry for the late response, just coming back to this now - I tried using the afterRestore as you suggested, and the issue I'm running into is that document is not defined by the time afterRestore runs.
That makes sense indeed.
I would still use the pinia-plugin-persistendstate and add your logic in your app.vue -> onMounted().