Skip to content

How to get reactive State on initial page load when using Fetch inside a Pinia Store #1078

Closed Answered by santosh898
markteekman asked this question in Help and Questions
Discussion options

You must be logged in to vote

@markteekman You have access to full composition api in the store definition function.

export const usePostsStore = defineStore('posts', () => {
  const posts = ref([])

  function getPosts() {
    fetch('https://mywebsite.com/wp-json/wp/v2/posts')
      .then(response => response.json())
      .then(data => {
        posts.value = data
        console.log('Data is fetched.')
      })
      .catch((error) => {
        console.log(error)
      })
  }

  // Runs the very first time the store is used. i.e., when the store is initialized.
  getPosts()

  return {
    posts,
    getPosts
  }
})

Replies: 3 comments 7 replies

Comment options

You must be logged in to vote
5 replies
@mpont91
Comment options

@vanillajonathan
Comment options

@markteekman
Comment options

@markteekman
Comment options

@tesfamariam1
Comment options

Comment options

You must be logged in to vote
1 reply
@markteekman
Comment options

Answer selected by markteekman
Comment options

You must be logged in to vote
1 reply
@tafadzwagonera
Comment options

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