Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vanilla js how to get latest value. in react work fine but when use in vanilla js only get old value #462

Open
StevePhuc opened this issue Feb 11, 2025 · 0 comments

Comments

@StevePhuc
Copy link

import { observable } from "@legendapp/state";
import { configureSynced } from '@legendapp/state/sync'
import { syncedSupabase } from '@legendapp/state/sync-plugins/supabase'
import { v4 as uuidv4 } from 'uuid';
import { supabase } from './index';
import { observablePersistIndexedDB } from "@legendapp/state/persist-plugins/indexeddb";
import { localDb$ } from "./local-db";
// Provide a function to generate ids locally
const generateId = () => uuidv4();

// Create a configured sync function
const customSynced = configureSynced(syncedSupabase, {
  persist: {
    plugin: observablePersistIndexedDB({
      databaseName: "UserDB",
      version: 1,
      tableNames: ["users"]
    })
  },
  generateId,
  supabase,
  changesSince: 'last-sync',
  fieldCreatedAt: 'created_at',
  fieldUpdatedAt: 'updated_at',
  // Optionally enable soft deletes
  fieldDeleted: 'deleted',
});

export interface Settings {
  sourceLang: string;
  targetLang: string;
  isPlayingTts: boolean;
  onboardingFinished: boolean;
}

export interface Browser {
  currentUrl: string;
}

export interface UserSettings {
  id: string;
  settings: Settings;
  browser: Browser;
  created_at?: string;
  updated_at?: string;
  deleted?: boolean;
}

export const users$ = observable<Record<string, UserSettings>>(
  customSynced({
    supabase,
    collection: 'users',
    initial: {},
    select: (from) =>
      from.select('*'),
    actions: ['read', 'create', 'update'],
    // realtime: true,
    // Persist data and pending changes locally
    persist: {
      name: 'users',
      retrySync: true, // Persist pending changes and retry
    },
    retry: {
      infinite: false, // Retry changes with exponential backoff
    },
  
  }),
);


export const initialUser = {
  settings: {
    sourceLang: 'en',
    targetLang: 'en',
    isPlayingTts: true,
    frontDelay: 3,
    backDelay: 3,
    showBackFirst: false,
    onboardingFinished: false,
  },
  browser: { currentUrl: 'https://google.com' },
}


export const getUserSettingsInit = () => {
  const userId = localDb$.userId.get();
  return users$[userId].get()?.settings || initialUser.settings;
}

export const setUserSettings = (newSettings: Partial<Settings>) => {
  const userId = localDb$.userId.get();
  if (!userId) return;
  users$[userId].settings.set({ ...users$[userId].settings.get(), ...newSettings });
}

when use in react it work fine when setUserSettings, get new value:

const userSettings = use$(getUserSettingsInit())

but when use in vanilla js (chrome extension service worker) , it alway get init value or old value so how to get update value
when call getUserSettingsInit() in vanilla js.
try to use


export const getUserSettingsInit = async () => {
const syncState$ = syncState(users$)
await when(syncState$.isPersistLoaded) // stop here and not continue it
  const userId = localDb$.userId.get();
  return users$[userId].get()?.settings || initialUser.settings;
}

but this not work , it just stop there when add it .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant