Unexpected behavior when dealing with stores (createStore)

Hello everyone, so I have this line of code:
{data.user ? <A href={`/years/${data.user.position || "fy"}`}>Begin studying</A> : <A href="/login"><FaBrandsMicrosoft /> Login</A>}
{data.user ? <A href={`/years/${data.user.position || "fy"}`}>Begin studying</A> : <A href="/login"><FaBrandsMicrosoft /> Login</A>}
It works perfectly but when the user logs out (user sets to null), they get this error in the console:
TypeError: Cannot read properties of null (reading 'position')
3 Replies
rarely active
rarely activeOP3mo ago
This is the logout function
const logout = () => {
setData("token", null);
setData("user", null);
localStorage.removeItem("token");
};
const logout = () => {
setData("token", null);
setData("user", null);
localStorage.removeItem("token");
};
peerreynders
peerreynders3mo ago
Try
<Show
when={data.user}
fallback={
<A href="/login">
<FaBrandsMicrosoft /> Login
</A>
}
>
{(user) => <A href={`/years/${user().position || 'fy'}`}>Begin studying</A>}
</Show>
<Show
when={data.user}
fallback={
<A href="/login">
<FaBrandsMicrosoft /> Login
</A>
}
>
{(user) => <A href={`/years/${user().position || 'fy'}`}>Begin studying</A>}
</Show>
If you are using the conditional operator in the component's return expression you are committing to one or the other JSX during setup time without any way to switch reactively later.
rarely active
rarely activeOP3mo ago
Noted, thanks Yeah it worked :D

Did you find this page helpful?