mirror of
https://github.com/myronblair/kino-app
synced 2026-06-30 17:50:16 -05:00
49 lines
1.3 KiB
React
49 lines
1.3 KiB
React
import { createContext, useContext, useEffect, useState, useCallback } from "react";
|
|
import api from "./api";
|
|
import { useAuth } from "./auth";
|
|
|
|
const ProfileCtx = createContext(null);
|
|
|
|
export const ProfileProvider = ({ children }) => {
|
|
const { user } = useAuth();
|
|
const [profiles, setProfiles] = useState([]);
|
|
const [active, setActive] = useState(null);
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
const refresh = useCallback(async () => {
|
|
if (!user) { setProfiles([]); setActive(null); return; }
|
|
setLoading(true);
|
|
try {
|
|
const { data } = await api.get("/profiles");
|
|
setProfiles(data);
|
|
const stored = localStorage.getItem(`kino_profile_${user.id}`);
|
|
const found = data.find((p) => p.id === stored);
|
|
setActive(found || null);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [user]);
|
|
|
|
useEffect(() => { refresh(); }, [refresh]);
|
|
|
|
const switchTo = (p) => {
|
|
if (!user) return;
|
|
localStorage.setItem(`kino_profile_${user.id}`, p.id);
|
|
setActive(p);
|
|
};
|
|
|
|
const clearActive = () => {
|
|
if (!user) return;
|
|
localStorage.removeItem(`kino_profile_${user.id}`);
|
|
setActive(null);
|
|
};
|
|
|
|
return (
|
|
<ProfileCtx.Provider value={{ profiles, active, loading, refresh, switchTo, clearActive }}>
|
|
{children}
|
|
</ProfileCtx.Provider>
|
|
);
|
|
};
|
|
|
|
export const useProfile = () => useContext(ProfileCtx);
|