Svelte Store 和异步本地存储(CapacitorJS 的首选项插件)

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

我有一个与同步 localStorage 配合使用的自定义商店。我想使用 capacitorjs 的首选项插件,但它是异步的。我的代码如下所示:

useStorage.js

const getItem = async (key) => {
    const { value } = await Preferences.get({ key: key });

    return value;
};

const setItem = async (key, value) => {
    await Preferences.set({
        key,
        value
    });
};

export function localStore(key, defaultValue) {
let serialize = JSON.stringify;
let deserialize = JSON.parse;

let storedValue;

const { subscribe, update, set } = writable(storedValue || defaultValue);
subscribe((value) => setItem(key, serialize(value)));

return {
    subscribe,
    async function() {
        const item = deserialize(await getItem(key));
        storedValue = item;
    },
    set
};

}

商店.js

export const name = localStore('name', 'your name');

现在发生的是将 $name 更新为另一个值也会在 localStorage 上更新它。但是当我重新加载时,它会恢复为默认值,因为获取存储值需要时间。有人知道解决方法吗?

javascript asynchronous svelte capacitor
1个回答
0
投票
1.First install
npm install @capacitor/preferences
npx cap sync

2.Then import
import { Preferences } from "@capacitor/preferences";

3.React js Code
let [step, setStep] = useState(1);

const setCpaStep = async (step) => {
    await Preferences.set({
        key: "capStep",
        value: step,
    });
};

const getCpaStep = async () => {
    const { value } = await Preferences.get({ key: "capStep" 
});
    const result = JSON.parse(value);
    console.log(`Step ${Number(result)}`);
    return Number(result);
};

const nextPage = () => {
    setStep((current) => current + 1);
    //localStorage.setItem("step", step + 1);
    setCpaStep(getCpaStep() + step);
};

const prevPage = () => {
    setStep((current) => current - 1);
    //localStorage.setItem("step", step - 1);
};
© www.soinside.com 2019 - 2024. All rights reserved.