You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SvelteKit中更新Local Storage内Store的方法及无效问题排查

问题分析与解决方案

核心错误点

  1. Store更新方式错误:你试图调用firmStore.firmName.set(),但firmStore是存储整个firm对象的writable store,并非包含子store的结构。writable store的set()/update()方法需直接调用在store实例上,不能访问内部属性的set方法。
  2. 默认对象布尔值错误:默认firm对象中的布尔字段被设为Boolean(构造函数),导致这些字段实际是函数而非布尔值,应改为false。
  3. LocalStorage读取逻辑错误:JSON.parse(browser && localStorage.getItem("firmStore"))在服务端环境下会执行JSON.parse(false),触发语法错误,需先判断浏览器环境再处理。
  4. Store初始值错误:writable(browser && storedFirm)在服务端会传入false作为初始值,不符合预期,应始终传入合法的firm对象。

修正后的Store代码

import { writable } from "svelte/store";
import { browser } from "$app/environment";

// 定义标准默认firm对象,布尔值设为false
const defaultFirm = {
    firmID: '',
    firmName: '',
    firmAddress: '',
    firmPhoneNumber: '',
    firmWebsite: '',
    firmType: '',
    firmMembers: [''],
    firmProjects: [''],
    firmRoles: [''],
    firmPermissionsID: '',
    firmComplete: false,
    completeYourProfile: false,
    buildYourTeam: false,
    definePermissions: false,
    aboutYourWork: false,
    errorConnectingToSupabase: false
};

// 安全读取LocalStorage:浏览器环境下优先取缓存,否则用默认值
const storedFirm = browser 
    ? JSON.parse(localStorage.getItem("firmStore")) || defaultFirm 
    : defaultFirm;

export const firmStore = writable(storedFirm);

// 订阅Store变化,同步到LocalStorage
firmStore.subscribe((val) => {
    if (browser) {
        localStorage.setItem("firmStore", JSON.stringify(val));
    }
});

修正后的Store更新代码

推荐使用update()方法修改单个/多个字段,避免覆盖未更新的属性:

import { firmStore } from "/src/stores/firmStore";

async function queryFirmDatabase(){
    const { data: firm, error } = await supabaseClient
          .from('firms')
          .select('id, firm_name,firm_address, firm_phone, firm_website, firm_projects, firm_complete, complete_your_profile, build_your_team, define_permissions, about_work')
          .eq('id', clientUser.orgID);

    if (firm) {
        const [fetchedUser] = firm;
        try {
            // 使用update方法合并现有数据与新数据
            firmStore.update(current => ({
                ...current,
                firmID: fetchedUser.id,
                firmName: fetchedUser.firm_name,
                firmAddress: fetchedUser.firm_address,
                firmPhoneNumber: fetchedUser.firm_phone,
                firmWebsite: fetchedUser.firm_website,
                firmProjects: fetchedUser.firm_projects,
                firmComplete: fetchedUser.firm_complete,
                completeYourProfile: fetchedUser.complete_your_profile,
                buildYourTeam: fetchedUser.build_your_team,
                definePermissions: fetchedUser.define_permissions,
                aboutYourWork: fetchedUser.about_work
            }));
        } catch (error) {
            console.log("更新Store失败:", error);
        }
    } else {
        console.log("从Firm数据库获取数据出错");
        console.log(error);
    }
}

调试说明

  • 查看Store实时值:在组件中使用console.log($firmStore)打印当前Store内容(Svelte中$前缀用于访问store的当前值)。
  • 验证LocalStorage:修改后刷新页面,在浏览器开发者工具的Application→Local Storage中检查firmStore键是否存在,内容是否正确。

内容的提问来源于stack exchange,提问作者ethanfox27

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:05:42