4

I am using Vuejs with Vuex and I have actions that are used to fetch data from the database, I want the fetch to be before rendering the components depended on this data. So where can I put these actions in my code ?

9
  • you can use created or mounted hook for the fetch operation. Note that created is called before mounted hook. Commented Mar 2, 2022 at 3:59
  • @sazzad mounted runs each time we access the component and I think created too, so we will have repetition, how to avoid that ? Commented Mar 2, 2022 at 4:08
  • @Omar don't you want to fetch data whenever component enter? Commented Mar 2, 2022 at 4:18
  • 1
    You can dispatch your actions inside the hooks beforeRouteEnter and/or beforeRouteUpdate. Commented Mar 2, 2022 at 7:45
  • 1
    @Omar It sounds unusual to me, logically need to fetch data from db every time enter page. If you want to do so you might need store a variable in browser storage to know that API has been fetched or not Commented Mar 2, 2022 at 15:22

2 Answers 2

6

You can use your action (ex: getData) on onMounted hook and you can use async await to be sure that your action call is done before moving to the next step

here is an exemple (i used axios just for the exemple you are free to use any methode to get your data) :

<template>
  <h1>My component</h1>
</template>

<script>
  import axios from 'axios'

  export default {

    name: 'MyComponent',

    setup() {
      const baseUrl = 'your-api-base-url'

      const apiClient = axios.create({
         baseURL: baseUrl,
         withCredentials: false,
         headers: {
           Accept: 'application/json',
           'Content-Type': 'application/json',
         },
      })

      const getData = async() => {
         try {
            return await apiClient.get('/api-path', {}) // here i call my 
              api to get data you can call your function
         } catch (error) {
            throw new Error(error)
         }
      }

      onMounted(() => {
        getData()
      })
    }
   }
 </script>
Sign up to request clarification or add additional context in comments.

4 Comments

return await apiClient.get({} + '/api-path') will trigger an error because {} + 'string' is a NaN
just a typo, it's must be apiClient.get({}, '/api-path') first param is the payload and seconde is the api path
i think you need to reverse {} and '/api-path' get function accept path as first parameter and object for the second
Fixed to apiClient.get('/api-path', {})
5

Mounted / BeforeMounted Created

On Vuejs 3 you have onMounted https://vuejs.org/api/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.