修改 Svelte 存储时如何更新 Firebase 实时数据库?

问题描述 投票:0回答:1

我见过很多从 Firestore 更新 svelte 存储的示例(请注意,我使用的是实时数据库),但我希望我的数据库根据对 svelte 存储的更改进行更新。目前我有很多类似这样的函数:

// Saves a list of the selected profiles to the scenario data
export const saveProfileData = (dataStore, sliderStore, popupIDs, scenarioID) => {
  const sliderData = get(sliderStore);
  const data = get(dataStore);

  const scenarioData = data[scenarioID]
  scenarioData.profileSave = {}
  for (const popupID of popupIDs){
    if (sliderData[popupID].hasOwnProperty("slider3")){
      scenarioData.profileSave[popupID] = sliderData[popupID].slider3.profile
    }
  } 
  dataStore.set(data)
}

其中

dataStore
是我的 Svelte 可写存储,我想将其与数据库同步(因为计算是在数据库的云函数中完成的)。请注意,我有一个单独的商店
sliderStore
,我没有同步。

我知道像

sveltefire
这样的事情会从服务器 -> UI 同步,所以我应该在函数而不是商店中更新我的数据库,然后以这种方式同步吗?

firebase firebase-realtime-database google-cloud-functions svelte sveltekit
1个回答
0
投票

如果您想根据 Svelte 存储中的更改来更新数据库,则需要有一种机制来检测存储中的更改并触发相应的数据库更新。由于您使用的是 Firestore 的实时数据库,因此您可能没有 Firestore 的 onSnapshot 等内置功能来进行实时更新。

以下是您可以采取的一般方法:

使用 Svelte 的商店订阅:Svelte 商店有一个订阅方法,允许您订阅更改。您可以使用它来检测商店中的变化。

触发数据库更新:当商店发生变化时,您可以触发一个函数来更新您的 Firebase 实时数据库。

这是一个简化的示例:

// dataStore.js
import { writable } from 'svelte/store';

const createDataStore = () => {
  const { subscribe, set } = writable({});

  return {
    subscribe,
    updateData: (newData) => set(newData),
  };
};

export const dataStore = createDataStore();

在您的组件中,您可以使用订阅来监听商店中的更改:

// Your Svelte component
import { onMount } from 'svelte';
import { dataStore } from './dataStore';

onMount(() => {
  const unsubscribe = dataStore.subscribe((newData) => {
    // Do something with the updated data, e.g., update the database
    updateDatabase(newData);
  });

  // Cleanup the subscription when the component is destroyed
  return () => unsubscribe();
});

现在,当你调用dataStore.updateData(newData)时,就会触发数据库更新函数(updateDatabase)。

请记住,updateDatabase 函数应根据您的特定数据库设置来实现。您可能需要使用 Firebase 等库来与实时数据库交互。

另外,要谨慎对待数据库更新的频率,以避免不必要的调用。如果您的商店经常发生变化,您可以考虑取消更新。

© www.soinside.com 2019 - 2024. All rights reserved.