I am trying to load some settings in onMount() function but it does not execute the onMount() first.
The other code inside script setup is executing and failing because the settings are not present. What is the correct way to load settings first inside script setup? Thanks for any suggestions.
<script setup>
import { storeToRefs } from 'pinia'
import { useAccountStore } from '../stores/account.store'
import { defineProps, reactive, ref, computed, onBeforeMount } from "vue";
import { useLoading } from 'vue-loading-overlay';
const accountStore = useAccountStore()
const { account, error, accountsettings } = storeToRefs(accountStore)
const props = defineProps({
id: {
type: String,
required: true,
}
});
const settings = accountsettings.value;
let type = settings.type;
//Other functions
async function load() {
await accountStore.loadSettings();
if (props.id) {
await accountStore.loadAccount(props.id);
}
};
onMount(() => {
console.log('mounting...');
load();
});
</script>
You cannot run OnMount
before Setup
.
There is a lifecycle rule and the first initialization is setup
. The onMounted
hook can be used to run code after the component has finished the initial rendering and created the DOM nodes.
For a better understanding, please have a look at the initialization life cycle diagram:
You must redesign your component taking into account that Setup is the first initialization.
Looking at your code, to load your settings, you could simply call await load()
at the end of your setup
script. It will run at the end of your initialization and you should avoid any errors. Like that, you can delete the hook onMount
.