i have a component that allows a user to select an option from a dropdown menu. The user’s selected is being set to localStorage, but i am wanting that localStorage value to be accessible to all other components in the project. I am thinking the way to make it globally accessible is to set a state.theme value equal to the value of the localStorage value. do you think this is an appropriate way of accomplishing the goal, and if so, how would i set a state.theme value to the localStorage value?
Hi @meaghan1,
You could set an action to modify that value in the state while writing that value in localStorage
.
https://docs.frontity.org/learning-frontity/actions
You also have to take into account that every time a page is reload the values stored in memory will be erased. So, you can use some of the “Actions triggered by Frontity” (afterCSR → afterClientSideRendering) to recover this data eery time a page is loaded
https://docs.frontity.org/learning-frontity/actions#actions-triggered-by-frontity
The code could be something like this…
import Theme from "./components";
const marsTheme = {
name: "@frontity/mars-theme",
roots: {
theme: Theme
},
state: {
theme: {
menu: [],
dropDownValue: 'none'
}
},
actions: {
theme: {
beforeSSR: before,
beforeCSR: before,
afterCSR: ({ actions }) => {
const dropDownValue = window.localStorage.getItem('dropDownValue')
if (dropDownValue) actions.theme.setDropDownValue(dropDownValue);
},
setDropDownValue: ({state}) => value => {
state.theme.dropDownValue = value;
window.localStorage.setItem('dropDownValue', value)
}
}
}
};
...
Hope this helps