Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pinia Init Action #1881

Closed
shba007 opened this issue Dec 18, 2022 · 2 comments
Closed

Pinia Init Action #1881

shba007 opened this issue Dec 18, 2022 · 2 comments

Comments

@shba007
Copy link

shba007 commented Dec 18, 2022

What problem is this solving

When useStore() called a init action should be called by default it will help to run some custom code which can be filling the state with data fetched from a server, And it should be called only when a store is installed

Proposed solution

export const useWishlist = () => {
  const innerStore = defineStore('wishlist', {
    state: (): { isInit: boolean} => ({
      isInit: false,
    }),
    getters: {
    },
    actions: {
      async init() {
       if (process.server || this.isInit)
          return
        this.isInit = true

     // TODO: Code to run
    },
  });

  const store = innerStore();
  store.init()

  return store;
}

Describe alternatives you've considered

  • process.server is there because for Nuxt when SSR happens the isInit changes to true and init is async so it does not get updated
  • If it is possible to hydrate the state from server side it will be more efficient ...but I am unable to done that
  • If I put isInit last init function will trigger multiple times if in a single page multiple component has same store
@posva
Copy link
Member

posva commented Dec 19, 2022

Duplicate of #1080

@posva posva marked this as a duplicate of #1080 Dec 19, 2022
@posva posva closed this as not planned Won't fix, can't repro, duplicate, stale Dec 19, 2022
@Farnsi
Copy link

Farnsi commented May 17, 2023

@shba007 with your solution the TypeScript typings will not work when you use e.g. with ...mapState(uswWishList,
The store itself will work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants