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 ?
2 Answers
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>
4 Comments
khofaai
return await apiClient.get({} + '/api-path') will trigger an error because {} + 'string' is a NaNSalma EL HAJRAOUI
just a typo, it's must be apiClient.get({}, '/api-path') first param is the payload and seconde is the api path
khofaai
i think you need to reverse {} and '/api-path' get function accept path as first parameter and object for the second
Salma EL HAJRAOUI
Fixed to apiClient.get('/api-path', {})
createdormountedhook for the fetch operation. Note thatcreatedis called beforemountedhook.mountedruns each time we access the component and I thinkcreatedtoo, so we will have repetition, how to avoid that ?beforeRouteEnterand/orbeforeRouteUpdate.