antfu-collective / vitesse

🏕 Opinionated Vite + Vue Starter Template
https://vitesse.netlify.app/
MIT License
8.84k stars 933 forks source link

[@vueuse useStorage] Lost data in localStorage when I refresh the page? dev normal. after build deploy error. #544

Open whoooami opened 1 week ago

whoooami commented 1 week ago

Describe the bug

When I login in my home page. 1、authStore.login(data); // checked the data was save in localStorage. 2、When I click refresh button of chrome. I see the "token" in localStorage change to empty string.

When I run "vite --port 3000 --open" in local. the token is ok. But When I run "vite-ssg build" and deploy to server. the token is missing when I refresh page.

I tried add ssr, but it still doesn't work.

ssr: {
    noExternal: ['@vueuse/core'], // 确保依赖正常工作
  },
import { useStorage } from '@vueuse/core'

export const useAuthStore = defineStore('auth', () => {
  const token = useStorage('token', '');

  const login = (user: any) => {
    const { token: newToken, ...userData } = user
    token.value = newToken
  }

  return {
    token,
    login,
  }
})

Reproduction

test url 1、open it. use chrome dev tools. set localStorage token anything in application. 2、refresh page. the token value is gone. tips: dev fine. build deploy to server, lost token. reproduction project.

System Info

npm: 21.1.0
pnpm: 9.11.0

Used Package Manager

pnpm

Validations

Contributions

whoooami commented 6 days ago

I tried like this, still doesn't work.

import { acceptHMRUpdate, defineStore } from 'pinia';

export const useInitStore = defineStore('init', () => {
  /**
   * Current name of the user.
   */
  const sd_id = import.meta.env.SSR? ref(""): useStorage("sd_id", "");
  const sd = import.meta.env.SSR? ref({}) : useStorage("sd", {});

  const setSd = (obj: any) => {
    console.log("setSd:", obj);

    const {id, ..._sd} = obj;
    sd_id.value = id;
    sd.value = _sd;
    if(!import.meta.env.SSR) {
      useStorage("sd_id", id);
      useStorage("sd", _sd);
    }
  }

  return {
    sd_id,
    sd,

    setSd,
  }
})

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useInitStore as any, import.meta.hot))