Home > Back-end >  Fetch data before rendering components in Vuejs
Fetch data before rendering components in Vuejs

Time:03-03

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 ?

CodePudding user response:

Mounted / BeforeMounted Created

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

CodePudding user response:

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>
  • Related