#How can I force re-rendering of parent component?

15 messages · Page 1 of 1 (latest)

frigid bluff
#

I am trying to use context that holds the theme (light|dark), I make a context in the root's component$, then from children when user login set the theme value using the useTask$, the problem is that the context is not updated in the parent. I made an experiment and added a toggle button, and then it seems works after the second click so, is it possible to force re-render?

alpine rover
#

Can you share your code or some parts of it?

frigid bluff
#

sure

#
const PageContext = createContextId<{ theme: string }>('page');

export default component$(() => {
    const pageContext = useStore({ theme: 'auto' }, { deep: true, reactive: true });

    useContextProvider(PageContext, pageContext);
    useContext(PageContext);

    return (
        <div data-theme={pageContext.theme}>
            theme={pageContext.theme}
            <hr />
            <InnerPage />
        </div>
    );
});

const InnerPage = component$(() => {
    const pageContext = useContext(PageContext);
    useTask$(() => {
        pageContext.theme = 'light';
    });
    return (
        <div>
            Inner
            <button onClick$={() => (pageContext.theme = 'dark')}>Set dark</button>
        </div>
    );
});
#

my usecase is using a layout, with dark/light switcher, but when user get logged in, then the switcher automatic sets to the value of the user setting to basically it sets from a route loader to the inner component

cursive otter
#

You should get a warning during SSR when you change a signal that a rendered component uses, did you not see one?

frigid bluff
#

I don't have such error, I have run it with dev mode

#

anyway, how can I achieve this behaviour then, I think it's pretty common usecase

cursive otter
#

For the theme switcher specifically, see the docs code. You need a script in head that adds the class depending on user preference, as well as CSS for the default.

rich ginkgo
frigid bluff
#

anyway, will use useVisibleTask$ for that, I was just disappointed that it doesn't works as I expected

frigid bluff
cursive otter
#

Wait I misunderstood - when the user logs in on the client, it should work. It can't work during SSR because then you want to change HTML that was already sent.