mitai-jinkendo/frontend/src/context/ProfileContext.jsx
Lars Stommer 89b6c0b072
Some checks are pending
Deploy to Raspberry Pi / deploy (push) Waiting to run
Build Test / build-frontend (push) Waiting to run
Build Test / lint-backend (push) Waiting to run
feat: initial commit – Mitai Jinkendo v9a
2026-03-16 13:35:11 +01:00

64 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createContext, useContext, useState, useEffect } from 'react'
import { useAuth } from './AuthContext'
const ProfileContext = createContext(null)
export function ProfileProvider({ children }) {
const { session } = useAuth()
const [profiles, setProfiles] = useState([])
const [activeProfile, setActiveProfileState] = useState(null)
const [loading, setLoading] = useState(true)
const loadProfiles = async () => {
try {
const token = localStorage.getItem('bodytrack_token') || ''
const res = await fetch('/api/profiles', {
headers: { 'X-Auth-Token': token }
})
if (!res.ok) return []
return await res.json()
} catch(e) { return [] }
}
// Re-load whenever session changes (login/logout/switch)
useEffect(() => {
if (!session) {
setActiveProfileState(null)
setProfiles([])
setLoading(false)
return
}
setLoading(true)
loadProfiles().then(data => {
setProfiles(data)
// Always use the profile_id from the session token not localStorage
const match = data.find(p => p.id === session.profile_id)
setActiveProfileState(match || data[0] || null)
setLoading(false)
})
}, [session?.profile_id]) // re-runs when profile changes
const setActiveProfile = (profile) => {
setActiveProfileState(profile)
localStorage.setItem('bodytrack_active_profile', profile.id)
}
const refreshProfiles = () => loadProfiles().then(data => {
setProfiles(data)
if (activeProfile) {
const updated = data.find(p => p.id === activeProfile.id)
if (updated) setActiveProfileState(updated)
}
})
return (
<ProfileContext.Provider value={{ profiles, activeProfile, setActiveProfile, refreshProfiles, loading }}>
{children}
</ProfileContext.Provider>
)
}
export function useProfile() {
return useContext(ProfileContext)
}