S
SolidJS15mo ago
pronoob

How can I stop code from executing before?

I am using @solidjs/router for routing, here's the code:
<Router>
<Routes>
<Route path="/" component={Guard}>
<Route path="/" component={Root} />
</Route>

<Route path="/login" component={Login} />
</Routes>
</Router>
<Router>
<Routes>
<Route path="/" component={Guard}>
<Route path="/" component={Root} />
</Route>

<Route path="/login" component={Login} />
</Routes>
</Router>
The Guard component checks for authentication (whether key is not in localStorage) in createEffect and navigates based on the result. The Root component is a protected component and only authenticated user can access it (localStorage contains the key item). The Root component looks something like this:
const Root: Component = () => {
const ws = new WebSocket("...");
ws.onmessage = e => {
console.log(e);
};

return <h1>Root</h1>;
};
const Root: Component = () => {
const ws = new WebSocket("...");
ws.onmessage = e => {
console.log(e);
};

return <h1>Root</h1>;
};
However, the WebSocket is connected before the Guard component validates and navigates the user.
3 Replies
Alex Lohr
Alex Lohr15mo ago
Why not create an Authenticated component that only renders its children if the user is authenticated?
pronoob
pronoob15mo ago
Example?
Alex Lohr
Alex Lohr15mo ago
Your current structure renders <Route><Guard/><Route><Root/></Route></Route>, but what you want is <Route><Guard><Root/></Guard><Route>. So in the JSX, you'd put in <Route path="/" component={<Guard><Root/></Guard>} /> and in Guard, you'd use <Show when={authenticated()} fallback={<Navigate ...>}>{props.children}</Show>
Want results from more Discord servers?
Add your server