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
}