Is there a way to get the user session and profile at the same time? The way I did it would be get the user session first after login then fetch the user profile using the id.
const [authsession, setSession] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
const userSession = supabase.auth.session();
setSession(userSession);
if (userSession) {
getProfile(userSession.user.id);
} else {
setSession((s) => ({ ...s, profile: null }));
}
supabase.auth.onAuthStateChange((_event, session) => {
setSession(session);
if (session) {
getProfile(session.user.id);
} else {
setSession((s) => ({ ...s, profile: null }));
}
});
}, []);
const getProfile = async (id) => {
setLoading(true);
setError(false);
try {
const { data } = await supabase
.from("profiles")
.select("*")
.eq("id", id)
.single();
setSession((s) => ({ ...s, profile: data }));
} catch (error) {
setError(true);
} finally {
setLoading(false);
}
};
The session.user object contains a property called user_metadata - this property contains the data which is present in the raw_user_meta_data column of the of auth.users table.
Hence, you can setup a DB trigger on your custom user profile table which copies the data from that table to the raw_user_meta_data column of the of auth.users table in JSON format anytime the data in the user profile table changes (i.e. you will need the trigger to be run on INSERT/UPDATE and probably DELETE statements). This way the profile data will be automatically delivered to the client with the sign-in or token refresh events.
IMPORTANT: This approach has potential drawbacks: