mirror of
https://github.com/nagaoo0/HabbitGrid.git
synced 2026-01-11 15:34:54 +00:00
EnsureLocalOnlyStorage Works correcly with new uuid system
This commit is contained in:
@@ -100,7 +100,11 @@ export async function saveHabit(habit) {
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
const { data, error } = await supabase.from('habits').insert(insert).select('*').single();
|
||||
const { data, error } = await supabase
|
||||
.from('habits')
|
||||
.upsert(insert, { onConflict: 'id' })
|
||||
.select('*')
|
||||
.single();
|
||||
if (error) {
|
||||
console.warn('Supabase saveHabit error, writing local:', error.message);
|
||||
return local.saveHabit({ ...habit, id });
|
||||
@@ -210,6 +214,8 @@ export async function syncLocalToRemoteIfNeeded() {
|
||||
let habits = local.getHabits();
|
||||
if (habits.length === 0) return localStorage.setItem(SYNC_FLAG, new Date().toISOString());
|
||||
habits = ensureUUIDs(habits);
|
||||
// Persist back to local so IDs match remote after upsert
|
||||
localStorage.setItem('habitgrid_data', JSON.stringify(habits));
|
||||
const rows = habits.map(h => ({
|
||||
id: h.id,
|
||||
user_id: user.id,
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
import { supabase } from './supabase';
|
||||
const STORAGE_KEY = 'habitgrid_data';
|
||||
|
||||
// UUID v4 generator for local/offline usage
|
||||
function generateUUID() {
|
||||
if (typeof window !== 'undefined' && window.crypto?.randomUUID) return window.crypto.randomUUID();
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
|
||||
const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
|
||||
export const getHabits = () => {
|
||||
try {
|
||||
const data = localStorage.getItem(STORAGE_KEY);
|
||||
@@ -56,14 +65,21 @@ const remoteMirrorDelete = async (id) => {
|
||||
|
||||
export const saveHabit = (habit) => {
|
||||
const habits = getHabits();
|
||||
// Respect provided id (e.g., UUID from AddEdit or datastore). Generate only if missing.
|
||||
const id = habit.id || generateUUID();
|
||||
const existingIndex = habits.findIndex(h => h.id === id);
|
||||
const newHabit = {
|
||||
...habit,
|
||||
id: Date.now().toString(),
|
||||
sortOrder: habits.length,
|
||||
createdAt: nowIso(),
|
||||
id,
|
||||
sortOrder: habit.sortOrder ?? habits.length,
|
||||
createdAt: habit.createdAt || nowIso(),
|
||||
updatedAt: nowIso(),
|
||||
};
|
||||
habits.push(newHabit);
|
||||
if (existingIndex >= 0) {
|
||||
habits[existingIndex] = newHabit;
|
||||
} else {
|
||||
habits.push(newHabit);
|
||||
}
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(habits));
|
||||
remoteMirrorUpsert(newHabit);
|
||||
return newHabit;
|
||||
|
||||
Reference in New Issue
Block a user