Is this Firebase Context correct?

I got this code online but not sure about it. Will the values come to me reactively. I'm worried that if I have a few protected(authenticated) routes, and firebase auth is still loading, then my user will get redirected to login page.
import { JSXElement, createContext, useContext } from "solid-js";
import { createStore } from "solid-js/store";
import { app } from "../configs/firebase";
import { Auth, getAuth, onAuthStateChanged, User } from "firebase/auth";

interface UserStore {
currentUser: User | null;
loading: boolean;
}

interface FirebaseStore {
user: UserStore;
auth: Auth;
}

const FirebaseContext = createContext<FirebaseStore>();

export const FirebaseProvider = (props: { children: JSXElement }) => {
const [user, setUser] = createStore<UserStore>({
currentUser: null,
loading: true,
});

const auth = getAuth(app);
onAuthStateChanged(auth, (currentUser) => {
setUser("currentUser", currentUser);
setUser("loading", false);
});

const store = {
user,
auth,
};

return (
<FirebaseContext.Provider value={store}>
{props.children}
</FirebaseContext.Provider>
);
};

export function useFirebase(): FirebaseStore {
return useContext(FirebaseContext)!;
// Non-null assertion as we'll always provide the context via FirebaseProvider
}
import { JSXElement, createContext, useContext } from "solid-js";
import { createStore } from "solid-js/store";
import { app } from "../configs/firebase";
import { Auth, getAuth, onAuthStateChanged, User } from "firebase/auth";

interface UserStore {
currentUser: User | null;
loading: boolean;
}

interface FirebaseStore {
user: UserStore;
auth: Auth;
}

const FirebaseContext = createContext<FirebaseStore>();

export const FirebaseProvider = (props: { children: JSXElement }) => {
const [user, setUser] = createStore<UserStore>({
currentUser: null,
loading: true,
});

const auth = getAuth(app);
onAuthStateChanged(auth, (currentUser) => {
setUser("currentUser", currentUser);
setUser("loading", false);
});

const store = {
user,
auth,
};

return (
<FirebaseContext.Provider value={store}>
{props.children}
</FirebaseContext.Provider>
);
};

export function useFirebase(): FirebaseStore {
return useContext(FirebaseContext)!;
// Non-null assertion as we'll always provide the context via FirebaseProvider
}
2 Replies
Brendonovich
Brendonovich8mo ago
Looks good, I’d suggest only calling setUser once and passing in both values rather than separately
ATA noob
ATA noobOP8mo ago
Thank you
Want results from more Discord servers?
Add your server