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?
#How can I force re-rendering of parent component?
15 messages · Page 1 of 1 (latest)
Can you share your code or some parts of it?
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
Your code should work but only on the client. During SSR it already output the div from the parent
You should get a warning during SSR when you change a signal that a rendered component uses, did you not see one?
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
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.
I had that issue and solved it by using useVisibleTask$ or adding isBrowser inside useTask$, depends of your needs, you can use also useOn()
Yes that's works, I just though it could works in SSR within the prerendering, because the data is there as it comes from the router action
anyway, will use useVisibleTask$ for that, I was just disappointed that it doesn't works as I expected
Well it's not only for the switcher, I think username that I display as the part of the menu is still very similar case
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.