Utilizing a function upon page initialization in VueX

I am currently learning Vue with Vuex and I have created a method called 'llamarJson' which is used to retrieve JSON data. However, I am facing difficulties in using this method when the page loads. I have tried various approaches but have not been able to find a solution. I am utilizing Vue and Vuex in my project. Can someone please assist me?

Below is the HTML code snippet:

<!DOCTYPE html>
<html>
<head>
    <title>Vue</title>
    <!-- Vue -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <!-- Vuex -->
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d1c0c0e253a3a3825241d14251b15">[email protected]</a>/dist/vuex.js"></script>
</head>
<body>

    <div id="caja-vue">
        <actividades></actividades>
    </div>
    


    <script src="codigo.js"></script>   
</body>
</html>

And here is the JS code section:

//components
Vue.component('actividades', {
    template: /*html*/
        `  <div>
            <h1>Hello friend</h1>
                <ul v-for="item of actividades">
                    <li>{{ item.name }}</li>
                </ul>
            </div>
        `,
    computed: {
        ...Vuex.mapState(['actividades'])
    },
    methods: {
        ...Vuex.mapActions(['llamarJson'])
    }
});

//Vuex
const store = new Vuex.Store({
    state: {
        actividades: [],
        programas: []
    },
    mutations: {
        llamarJsonMutation(state, llamarJsonAction){
            state.actividades = llamarJsonAction;
        }
    },
    actions: {
        llamarJson: async function(){
            const data = await fetch('https://jsonplaceholder.typicode.com/users');
            const actividades = await data.json();
            commit('llamarJsonMutation', actividades);
        }
    }
});

//Vue
new Vue({
    el: '#caja-vue',
    store: store
});

Answer №1

To achieve this, it is recommended to utilize the Vue life cycle hooks. You can find more information on this topic by following the link provided below:

Vue life cycle hooks

The following are some of the Vue hooks available:

Creation Hooks

beforeCreate(): Initializes events and lifecycle without making data reactive

created(): Provides access to reactive data and events but templates and virtual DOM have not been mounted or rendered yet

Mounting Hooks

beforeMount(): Executes before the initial render

mounted(): Grants access to the reactive component, templates, and rendered DOM

Updating Hooks

beforeUpdate(): Runs after data changes and before re-rendering the DOM

updated(): Executed after data changes and the DOM has been re-rendered

Destruction Hooks

beforeDestroy(): Triggers prior to tear down

destroyed(): Activated after tear down

Depending on your requirements for page load (access to the DOM or not), you may choose to use either the created() or mounted() hooks.

You can simply define these hooks within your Vue component object and call your desired method within them as demonstrated below:

created() {
  this.someMethod();
}

In your specific case, you could directly call the Vuex action from the created hook (or any other hook) like so:

created() {
  this.$store.dispatch('vuexAction');
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process of using JavaScript code to read a text file?

Trying to use Google Charts while reading data from a text file. The code in JS is written for this purpose: function readTextFile(file){ var rawFile = new XMLHttpRequest(); rawFile.open("GET", file, false); // using synchronous call var allTe ...

When a Vue.js datepicker is set as required, it can be submitted even if

When using the vuejs-datepicker, setting the html required attribute on input fields may not work as expected. This can lead to the form being submitted without an input value. <form> <datepicker placeholder="Select Date" required></datep ...

Using PHP and AJAX, populate a table based on the selection made from a dropdown

Hello, thank you for taking the time to review my issue. Let me outline the objective. I have successfully implemented two drop-down menus that are populated dynamically from a database. The query retrieves names and phone numbers (with plans to fetch mor ...

Achieving successful content loading through AJAX using the .load function

Our website features a layout where product listings are displayed on the left side, with the selected product appearing on the right side (all on the same page). Initially, when the page loads, the first product is shown on the right. Upon clicking a new ...

Angular promise fails to resolve after an extended period of waiting for a response

My application is designed to send GET requests to my node/express server. In order to monitor changes in the server code, I have implemented a setTimeout function. While the promise function on the client side initially functions properly for a short peri ...

$injector.modulerr problem

After spending a considerable amount of time analyzing every line of code, I can't seem to pinpoint any errors. Here is what I have: HTML: <body ng-app='myApp'> <div class="wrapper"> <nav> <ul ng-controller="pat ...

"Transforming a simple object into an instance of a different type in JavaScript: A step-by-step guide

Having an issue storing a session on disk for local development. The application is asking for an instance of Session to be returned, not an Object function storeCallback(session) { console.log("storeCallback ", session); fs.writeFileSync(&qu ...

Creating an overlay with CSS hover on a separate element and the ::before pseudo class

Issue: I am struggling to display the overlay when hovering over the circle element, rather than just the image itself. I have attempted to achieve this using CSS, but can't seem to make it work as intended. Any guidance and examples using JavaScript ...

What is the best way to align flexbox to the left?

I'm having trouble aligning the FileCard component to the start of the container. I attempted using flex-start in my styling, but the FileCards are still centered. This is the current code snippet: <div v-if="posts" ...

I am encountering an issue where the useState hook is returning an undefined value on separate components, even after

When setting up a login context, I wrap all my routes with the context provider and pass the initial value using useState: <userContext.Provider value={{loggedUser, setLoggedUser}}> In LogInMenu.jsx, which is responsible for setting the loggedUser ( ...

What steps can I take to address this Material UI alert and deliver a solution that adds value?

I am currently working on fetching API data (specifically category names) from the back-end (Node.js) to the front-end (React). My main objective right now is to populate a Select component from Material UI. To fetch the API data, I am utilizing Express an ...

Tips for capturing all mobile events in Angular

Trying to capture all mobile events like touch and swipe, I have added event listeners at the document level: document.addEventListener('tap', trackTouchActivity, false); document.addEventListener('swipe', trackTouchActivity, false ...

What is the process for exporting a plugin from dayjs() in JavaScript?

Currently, I have incorporated the plugin isToday() to enhance the capabilities of dayjs(). Nevertheless, I am uncertain about how to export isToday() in order to utilize it across other files. import isToday from "dayjs/plugin/isToday"; expor ...

How do I combine Firefox binary specification with adding the Firebug extension when using Selenium?

Presently I am utilizing the code below. var co = require('co'); var WebDriver = require('selenium-webdriver'); var SeleniumServer = require('selenium-webdriver/remote').SeleniumServer; co(function *() { // async var ser ...

Retrieve a file from an AWS S3 bucket using AngularJS

Currently utilizing angularjs. I am in need of incorporating a download feature. <button class="btn btn-labeled btn-info" title="download"> <a href="link provided by s3" download="downloaded">Download</a> </button> I have ...

Why doesn't ngSubmit function inside a modal?

I am experiencing an issue where my submit button is not activating the ng-click angular directive, and I cannot seem to identify the cause. Most people who faced a similar problem did not have their submit button placed inside their form, but I am confi ...

Vue Single Page Application - invoking methods across all components

I am currently developing a notification feature that can be triggered from any component. It utilizes a straightforward Vuetify v-snackbar. Within App.vue <router-view :key="$route.fullPath"></router-view> <v-snackbar :valu ...

Should reports be created in Angular or Node? Is it better to generate HTML on the client side or server side

I have a daunting task ahead of me - creating 18 intricate reports filled with vast amounts of data for both print and PDF formats. These reports, however, do not require any user interaction. Currently, my process involves the following: The index.html ...

Three.js experiences a memory leak issue

We are currently working on a single page app where users can switch between multiple Three.js apps. However, we have observed a continuous increase in memory usage by the tab. There is no memory leakage in our app and it appears that Three.js variables ar ...

Can anyone tell me the method to retrieve the id of the current element that initiated the horizonSwiper event in JavaScript?

I successfully integrated horizonSwiper into my php(Yii2) website to display images from different albums in a horizontal row with the ability to scroll left and right. Now, I am looking to implement lazy loading when scrolling or swiping left/right. Howev ...