SolidJSS
SolidJSโ€ข3y agoโ€ข
5 replies
gmnss1917

PocketBase Auth with Context doesn't track store

I'm trying to create a PocketBase AuthContext that I may add to my app, so that in the future if I wish to add more routes I can access the data from all the routes. However this is getting on my nerves, because the store isn't tracking when the pb.authStore changes (creation / deletion / updated), that is except when HMR kicks in, then it refreshes. And the weirdest part is I can log it on the console...

Here is the code:

const AuthContext = createContext<
  { token: string; model: AuthModel } | string
>();

export function AuthProvider(props: { children: JSX.Element }) {
  //kind of a singleton, supposedly (in my mind, as this will only run once)
  const pb = createMemo(() => new PocketBase("http://127.0.0.1:8090"));
  
  createEffect(() => console.log(pb().authStore.model));

  //store for auth token and user data
  const [{ token, model }, setState] = createStore({
    model: pb().authStore.model,
    token: pb().authStore.token,
  });

  //subscribing to changes on the authStore so that it updates the solid store
  createEffect(() => {
    pb().authStore.onChange((tok, mod) => {
      setState(reconcile({ model: mod, token: tok }));
      console.log("authStore changed: ", model);
    });
  });
  return (
    <AuthContext.Provider value={{ token, model }}>
      {props.children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}
Screenshot_from_2023-08-29_20-25-41.png
Was this page helpful?