Perspective Component Detect Theme Change

I need to programatically set the theme on a component I'm currently working on, and was wondering the best way to detect it? I was trying the code below

    const [theme, setTheme] = useState(store.props.read("session.props.theme"));
    useEffect(() => {
        const unsubscribe = store.props.subscribe((store) => {
            setTheme(store.read("theme"));
        });
        // Cleanup subscription on component unmount
        return () => {
            unsubscribe();
        };
    }, [store]);

Bumping this - is there a good way to subscribe to this variable?

Perspective/component development isn't my forte, but subscribing to the state of the theme seems like potentially an antipattern - shouldn't the theme be delivering whatever style information your components are using?

That aside, what you're doing seems fine?

Yeah I guess my problem is that my component isn't noticing the theme/css updates and I have to force it to update (underlying tool isn't a native react component so I have to call a repaint() to get it to update sometimes).

My code above doesn't seem to be working sadly. I'm getting undefined for the theme, so not sure if I have the path wrong or what I need to do there.

You should be accessing the session properties from the tree attached to the PageStore:

props.store.clientStore?.page?.sessionProps?.subscribe((tree) =>
  console.log(tree.read('theme'))
)
1 Like