Skip to content

Initialize state with calling an action that makes an API call #1176

Closed Answered by dreambo8563
mpont91 asked this question in Help and Questions
Discussion options

You must be logged in to vote

@mpont91 I am trying to have a wrapper as a solution, any place using const xx = useDemoStore() won't need to change. all usage will be the same as normal store

export const useDemoStore = () => {
  const innerStore = defineStore({
    id: "demo",
    state: () => ({
      counter: 0,
    }),

    actions: {
      asyncList() {
        console.info("asyncList");
        setTimeout(() => {
          this.counter = 100;
        }, 1000);
      },
    },
  });
  const s = innerStore();
  if (s.counter == 0) {
    s.asyncList();
  }
  return s;
};

Replies: 3 comments 8 replies

Comment options

You must be logged in to vote
8 replies
@tmountjr
Comment options

@katerlouis
Comment options

@tmountjr
Comment options

@skjnldsv
Comment options

@yuya737
Comment options

Answer selected by mpont91
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
10 participants