Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

boyjarv's avatar

refreshing my app breaks and user state sets back to null

Why is my App breaking when I refresh my browser?

https://github.com/jbiddulph/spa-challenge

0 likes
6 replies
vincent15000's avatar

Thank you for sharing your code on github, but you can also explain here what you have tried to identify the problem.

Niush's avatar

Looking through the code, I think, something like this might better initialize the state. If that is the issue you are facing.

// /src/store/modules/auth/index.js

export default {
  namespaced: true,
  state() {
    let userData = JSON.parse(localStorage.getItem("userData"));

    return {
      name: userData?.name || "",
      email: userData?.email || "",
      // ...
    };
  },
  // ...
};
1 like
boyjarv's avatar

Thanks @niush I have changed my auth/index.js to this:

import mutations from "./mutations";
import getters from "./getters";
import actions from "./actions";

export default {
  namespaced: true,
  state() {
    let userData = JSON.parse(localStorage.getItem("userData"));
    console.log("UserData:" + JSON.stringify(userData));
    return {
      name: userData?.name || "",
      email: userData?.email || "",
      token: userData?.token || "",
      userId: userData?.userId || "",
      autoLogout: false,
    };
  },
  mutations,
  getters,
  actions,
};

I am still losing the username when I refresh the browser after logging in

Niush's avatar

@boyjarv Have you checked the Vue DevTools to see Vuex mutation history? It can help you identity what action caused it to reset back.

martinbean's avatar

Why is my App breaking when I refresh my browser?

@boyjarv I imagine because the default state is empty. So yes, if you refresh the browser, then the default state is going to be rendered again.

Please or to participate in this conversation.