SolidJSS
SolidJSโ€ข11mo agoโ€ข
3 replies
noxy

navigate - Wait for navigation to finish

Hello, I'm reevaluating SolidJS and somehow it started really click in my head. There's one thing that I'm trying to do right now, basically I'm wrapping my whole app with UserProvider and and to expose two 'hooks' useUser and useMaybeUser with the only difference between them being that useUser would enforce that user is present or navigate you to login page.

Here's what I came up with for now.
import { useNavigate } from "@solidjs/router";
import {
  createContext,
  createResource,
  type Resource,
  Suspense,
  useContext,
  type ParentComponent,
} from "solid-js";
import { getApiAuth, type User } from "~/client";
import { client } from "~/client/client.gen";

export const UserContext = createContext<Resource<User | undefined>>();

export function useMaybeUser() {
  const user = useContext(UserContext)!;
  return user();
}

export function useUser() {
  const user = useContext(UserContext)!;
  if (!user()) {
    const navigate = useNavigate();
    navigate("/api/auth/signin-google", { replace: true, resolve: true });
    throw Error("unreachable");
  }
  return user();
}

export const UserProvider: ParentComponent = (props) => {
  const [user] = createResource(() =>
    getApiAuth({ client }).then((r) => r.data?.user)
  );

  return (
    <UserContext.Provider value={user}>
      <Suspense>{props.children}</Suspense>
    </UserContext.Provider>
  );
};

This code seems to be triggering 'unreachable' error. I'm wondering what would be the best way to wait for navigation to finish so 'unreachable' error is actually never reached?
Was this page helpful?