troubleshooting vuex and axios

Feeling overwhelmed, I successfully integrated a working API with my VueJS app but hit a roadblock when implementing Vuex. Here's the snippet from my store.js file:

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios'
Vue.use(Vuex);

const state = {
        message: "I am groot",
        articles: []
    }
const getters = {
        getArticles: (state) => {
            return state.articles;
        }
    }
const actions = {
          getArticles: ({ commit }, data) => {
            axios.get('/articles').then( (articles) => {
                commit('GET_ARTICLES', articles);
                console.log(articles); // Debugging
            }, (err) => {
                console.log(err);
            })
          }
    }
const mutations =  {
        GET_ARTICLES: (state, {list}) => {
            state.articles = list;
        }   
    }
const store = new Vuex.Store({
    state,
    getters,
    mutations,
    actions,
    mutations
});
console.log(store.state.articles); // Data is empty here
export default store

The console.log inside the axios call isn't executing and the store.state.articles remains empty. It seems like something critical is missing in my setup. All I want is to display the articles data when the page loads...

Please lend me a hand, this issue is driving me crazy :)

Component :

<template>
  <div class="container">
    <h1>Test component yo !</h1>
    <p>{{ message }}</p>
  </div>
</template>

<script>
    export default {
        name: 'Test',
        computed: {
            message() {
                return this.$store.state.message
            }
        },
        mounted: () => {
            this.$store.dispatch('getArticles')
        }

    }
</script>

App.js :

import Vue from 'vue';
import ArticlesViewer from './articles_viewer.vue';
import UserArticles from './user_articles.vue';
import App from './app.vue'
import store from './store'

new Vue({
  el: '#app-container',
  store,
  render: h => h(App)
})

Answer №1

One way to define the mounted lifecycle hook of your component is by using an arrow function.

According to the information provided in the documentation:

Avoid using arrow functions on an instance property or callback (e.g.

vm.$watch('a', newVal => this.myMethod())
). Since arrow functions are tied to the parent context, this will not refer to the Vue instance as expected and this.myMethod will be undefined.

The recommended way to define it is:

mounted: function () {
  this.$store.dispatch('getArticles');
}

Alternatively, you can use the ECMAScript 5 shorthand:

mounted() {
  this.$store.dispatch('getArticles');
}

By following these guidelines, your dispatch method will be executed correctly, resulting in your articles array being populated.

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

"Implementing an AngularJS factory that returns a State object instead of typical JSON data fetched from

I have created two factories and I am calling the first one from the second one in my controller. However, instead of receiving JSON data, I am getting data as $$State. I am new to AngularJS and have tried multiple solutions but have not been able to resol ...

"Struggling to make the 'overflow: hidden' property work for an absolutely positioned

I'm struggling to conceal an absolutely positioned image within a CSS grid layout. Below is the code snippet: HTML: <div class="relative-parent"> <div v-for="item in 12" class="hiding-parent"> <div c ...

Having trouble getting Tesseract.js to work with an Electron App built using Vue and vue-cli-plugin-electron-builder

Struggling with using Tesseract OCR in a project created with vue-service-cli? You're not alone. I've been facing issues trying to load lang.traineddata both locally and remotely. Despite attempting various solutions found in tesseract.js repo an ...

Troubleshooting async/await issues in certain IDEs

I've been experimenting with aysnc and await in my project. While it worked perfectly in FiddleJS, I encountered an error when trying to implement it in my IDE (PHPSTORM 2017): async function test(url){ ^^^^^^^^ SyntaxError: Unexpected token f ...

Assigning a Value to a Select Option in a Dynamically Generated Form

I've developed a dynamic form that includes a dropdown menu. I would like this dropdown to display fiscal weeks, and to achieve this, I need to implement a loop within a TypeScript function. form.ts - <div class="col-md-9" [ngSwitch]="field.type ...

Designing a JSON array

How can I format my JSON list into Material Cards? Here is my JSON/JavaScript code: $(document).ready(function(){ var url="getjson.php"; $.getJSON(url,function(data){ console.log(data); $.each(data.bananas, function(i,post){ ...

Leverage ConvexGeometry within the npm release of THREE

Is there a way to utilize ConvexGeometry in the npm version of THREE? It appears that it was introduced in r85: https://github.com/mrdoob/three.js/releases I noticed that it's only present in the example folder. Is there a method to incorporate it ...

Vue-Router implementation utilizing the onReady() method

As a newcomer to Vue, I'm eager to learn about when the onReady() function will be triggered. The explanation in the Vue Router documentation states: This method queues a callback to be called when the router has completed the initial navigation, w ...

stay at the top of the screen with anchor #link

Is there a way to link to a page with a specific bootstrap nav-tabs open without the page automatically scrolling down to that tab? I've tried using #link with the tab id, like www.mysite.com/apagewithtabs#tab2, but I want the user to be at the top of ...

Be cautious of potential issues with arrays in React JS

I have a function that handles state updates based on incoming props static getDerivedStateFromProps(nextProps, prevState) { let { fetching } = nextProps const { error } = nextProps if (prevState.fetching !== fetching && !fetching) { fe ...

Utilizing numerous X-axis data points in highcharts

I'm working with a line graph that dips straight down, like starting at (1, 100) and dropping to (1,0). The issue I'm facing is that Highcharts (https://www.highcharts.com/) only displays information for one of the points. Is there a way to make ...

What is the process for sending JavaScript data to a Rails controller action?

Utilizing jQuery Shapeshift for drag and drop reordering of lists on my web application. I am looking to send the data below to my Rails controller action in order to update the list's order. Every time I drag a list, this is the output that appears ...

Is there a way to access the value of a variable in Express that is stored in a different file?

Looking for a way to fetch the value of a variable that is located inside app.use? chatbot.js: const express = require('express'); const app = express.Router(); app.use(['/chat', '/chatbot'], (req, res, next) => { const ...

Exploring Next.js: Advanced capabilities of shallow routing in combination with dynamic routes

Many people seem to be confused about the behavior of shallow routing with dynamic routes in Next.js. When attempting shallow routing, the page is refreshed and the shallow option is ignored. Let's consider a scenario where we start on the following ...

Is it possible for setTimeout to not increment the counter in node.js?

Even though the loop is executed multiple times in the Node.js program below, why does the control not exit the loop? I made sure to increment the value of i within setTimeout instead of forgetting to do i++ in the for loop. function abc () { for(var ...

The output from the console displays a variety of numbers (11321144241322243122)

Every time I attempt to log the number 11321144241322243122 into the console, it consistently converts to a different number 11321144241322244000. This issue persists both in node.js and the browser console. ...

Finding the number of parameters in an anonymous function while using strict mode can be achieved through which method?

Is it possible to determine the arity of a function, such as the methods.myfunc function, when using apply() to define the scope of this and applying arguments? Following the jQuery plugin pattern, how can this be achieved? (function($, window, document ){ ...

ASP.NET "Data" Error: Trouble Parsing JSON Data on the Front-End

I am currently facing an issue with the configurations on my asmx page. The code is set up like this: using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Script.Serialization; using Syst ...

Finding specific data within a nested HTML name array using either JQuery or JavaScript based on the second level key

Is there a way to target all input elements with names that contain 'pref[*][location][]' using a jQuery selector or JavaScript? Specifically, I want to retrieve those inputs based on the 'location' key in the second level. <input ty ...

jQuery failing to transmit JSON in AJAX POST call

I'm a bit perplexed at the moment, as I'm attempting to send data to my Node.js server using the code snippet below: $.ajax({type:'POST', url:'/map', data:'type=line&geometry='+str, succe ...