mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 15:51:12 -05:00
Fix unit preferences logic
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { UnitPreferences, getMeasurementSystemFromCountry } from '@/lib/units';
|
||||
@@ -56,14 +56,11 @@ export function useUnitPreferences() {
|
||||
}
|
||||
};
|
||||
|
||||
const autoDetectPreferences = async () => {
|
||||
console.log('🌐 Calling edge function for location detection...');
|
||||
const autoDetectPreferences = useCallback(async () => {
|
||||
try {
|
||||
const response = await supabase.functions.invoke('detect-location');
|
||||
console.log('📡 Edge function response:', response);
|
||||
|
||||
if (response.data && response.data.measurementSystem) {
|
||||
console.log('🎯 Detected measurement system:', response.data.measurementSystem);
|
||||
const newPreferences: UnitPreferences = {
|
||||
...DEFAULT_PREFERENCES,
|
||||
measurement_system: response.data.measurementSystem,
|
||||
@@ -71,25 +68,34 @@ export function useUnitPreferences() {
|
||||
|
||||
setPreferences(newPreferences);
|
||||
|
||||
// Save to localStorage for anonymous users
|
||||
if (!user) {
|
||||
// Save to database for logged-in users, localStorage for anonymous users
|
||||
if (user) {
|
||||
// Use upsert with merge
|
||||
const { error } = await supabase
|
||||
.from('user_preferences')
|
||||
.upsert({
|
||||
user_id: user.id,
|
||||
unit_preferences: newPreferences as any,
|
||||
updated_at: new Date().toISOString()
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error('Error saving preferences to database:', error);
|
||||
}
|
||||
} else {
|
||||
localStorage.setItem('unit_preferences', JSON.stringify(newPreferences));
|
||||
console.log('💾 Saved preferences to localStorage:', newPreferences);
|
||||
}
|
||||
|
||||
return newPreferences;
|
||||
} else {
|
||||
console.log('⚠️ No measurement system in response');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Error auto-detecting location:', error);
|
||||
}
|
||||
|
||||
// Fallback to default
|
||||
console.log('🔄 Falling back to default preferences');
|
||||
setPreferences(DEFAULT_PREFERENCES);
|
||||
return DEFAULT_PREFERENCES;
|
||||
};
|
||||
}, [user]);
|
||||
|
||||
const updatePreferences = async (newPreferences: Partial<UnitPreferences>) => {
|
||||
const updated = { ...preferences, ...newPreferences };
|
||||
@@ -101,7 +107,7 @@ export function useUnitPreferences() {
|
||||
await supabase
|
||||
.from('user_preferences')
|
||||
.update({
|
||||
unit_preferences: updated,
|
||||
unit_preferences: updated as any,
|
||||
updated_at: new Date().toISOString()
|
||||
})
|
||||
.eq('user_id', user.id);
|
||||
|
||||
Reference in New Issue
Block a user