In what ways do getters, mutations, and actions collaborate within the Vuex architecture?

Exploring Vuex for my personal project has piqued my interest, particularly in understanding how the various properties interact. I hope this question isn't too redundant.

I've set up my store in Vue3 as follows:

// store/index.js
import { createStore } from "vuex";
import axios from "axios";
let connected = false;
axios.defaults.withCredentials = true;
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;
export default createStore({
  state: {
    connected,
  },
  getters: {
    getConnected: (state) => {
      return state.connected;
    },
  },
  mutations: {
    setConnected(state, isConnected) {
      console.log("in mutations");
      return (state.connected = isConnected);
    },
  },
  actions: {
    isConnected: ({ commit }) => {
      axios
        .get("/auth/me")
        .then(() => {
          console.log("here positive");
          commit("setConnected", true);
        })
        .catch(() => {
          console.log("here negative");
          commit("setConnected", false);
        });
    },
  },
  modules: {},
});

The state represents what we're storing, the mutations handle operations on the state, and the actions manage the mutations via commits.

Below is my Vue page setup:

<template>
  <v-row justify="start">
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link :to="connected ? '/me' : '/signup'">{{
        connected ? "Profile Page" : "Sign up"
      }}</router-link>
      |
      <router-link :to="connected ? '/logout' : '/login'">{{
        connected ? "Logout" : "Login"
      }}</router-link>
    </nav>
  </v-row>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
export default {
  name: "NavBar",
  data() {
    return {
      connected: false,
    };
  },
  methods: {
    ...mapGetters(["getConnected"]),
    ...mapActions(["isConnected"]),
  },
  mounted() {
    this.connected = this.getConnected();
    console.log("connected", this.connected);
  },
};
</script>

<style>
nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>

My query pertains to triggering the actions. Should I explicitly invoke the method using mapActions, or is there something I might be overlooking?

Thanks in advance!

Answer №1

To utilize this method, simply call it like so:

async mounted() {
  await this.checkIfConnected()
  this.connectionStatus = this.retrieveConnectionStatus();
  console.log("Connection Status:", this.connectionStatus);
},

For further details, click here

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

Encountering a Laravel error: Unexpected token when implementing Vuex

Recently, while working with Laravel and Vue.js, I encountered an unexpected token error when trying to access a method from my store using Vuex mapAction. The issue lies within the three dots (...) before the mapActions in the following code snippet foun ...

Utilizing shared code among various AngularJS projects

As a beginner in AngularJS, I am curious about the recommended approaches for sharing common javascript code among different AngularJS projects. I would love to hear some insights from seasoned AngularJS experts on this topic! I've come across menti ...

The latest error in the Next.js 13 app directory: React child is not valid (detected: [object Promise])

I am currently utilizing the new app directory feature in Next.js 13. Within my project, I have a page component located at app/page.tsx. This component contains the following code snippet: "use client"; import { useState } from "react" ...

Leveraging vuex within a vue component that has been mounted manually

I've been manually mounting a component onto a dynamic element using Vue.extend with the following code snippet: import Vue from 'vue'; import MyComponent from 'MyComponent.vue'; const MyComponentConstructor = Vue.extend(MyCompon ...

Invoke Web Communication Foundation service using JavaScript on an HTML webpage

I am working on a WCF project in VSStudio2012 and I need to execute a method from a JavaScript function. Here is the JavaScript file: var url = 'http://localhost:52768/Service1.svc/' function test() { var response; $.ajax({ type: 'P ...

Creating a targeted jQueryUI tab focus

My jQueryUI tabs have a click function defined on a specific tab which works correctly with ajax calls: $("a[href='#tabs-1ua']").click(function (event, ui) { //ajax call }); Now I want to capture not just clicks but any type of focus on thi ...

PWA JavaScript struggling with GPS geolocation coordinates

I am experiencing issues with the GPS coordinates being stuck when using geolocation in a Progressive Web App (PWA). Sometimes, the coordinates get stuck at the previous location, even if the user has moved since then. I suspect that this is due to the GP ...

The serialize() method in Ajax is not capturing all the data fields from an HTML form

Attempting to use the jQuery get() method to send form data from my website, I encountered an issue where only a few of the field data were actually transmitted to the server upon form submission. The Form: <form class="form-horizontal" id="addpost" ...

What is the process for updating or upserting a document in Mongoose?

Maybe it's the timing, maybe it's me struggling with sparse documentation and not quite grasping the concept of updating in Mongoose :) Let's break it down: I have a contact schema and model (abbreviated properties): var mongoose = requir ...

What is the best way to dynamically set the 'selected' attribute in HTML dropdown options using AngularJS data?

I'm currently in the process of developing an angularJS application. Below is a snippet of my PHP code: <label class="item item-input item-select"> <div class="input-label">Do you possess the right to work in the UK?</div> & ...

Eliminating unwanted hash symbols in URLs while utilizing the $routeProvider feature in AngularJS

Upon starting my application, it automatically opens the following URL: http://localhost:8080/#/. I am attempting to have it open this URL instead: http://localhost:8080/ when the application loads, but I haven't been successful in doing so. I am usi ...

JavaScript: unable to locate information within JSON reply

Looking to develop a Twitter bot utilizing the Twitter and Spotify APIs. Making progress, but encountered an issue I can't tackle alone: Seeking the artist and song name of the top 1 track from the top 50 Spotify songs. Upon sending a request to the ...

Switch navigation - always display the menu on the existing page

I have a toggle menu implemented. Please check out the code and functionality on JsFiddle When clicking on a h3 tag like Category 1 (which is an a tag), the menu opens and remains open on the current page. However, if you click on the h3 tag (Category1) ...

Having trouble launching my Angular project

After encountering issues with my Angular project, I decided to reinstall Node.js and Angular CLI. However, when attempting to run ng serve, I was met with this error: view the image here I conducted a thorough search on Google for a solution, which direc ...

What is the best way to fetch values from individual buttons using PHP?

<form action="posts-ayarlar.php" method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left"> <table class="table table-striped table-bordered" ...

What could be the reason behind the validation failure of this Javascript code?

After implementing your recommendation, this is my current status: <script> function tick() { const React.element = ( '<div><marquee behavior="scroll" bgcolor="lightyellow" loop="-1" width="100%"> <i> <font color ...

Tips for optimizing character count for mobile web pages with varying screen sizes and font settings

As I embark on developing an eBook mobile app, I am faced with various considerations such as screen size, font size, and determining the number of paragraphs to include on a single page based on the current screen and font settings. My aim is to adjust t ...

Build a dynamic checkbox list using DOM manipulation in JavaScript, populating it with values from an array

I am looking to create a checkbox list in JavaScript populated with names of animals from an array, and then display them in HTML. Here is my attempt at the code: var animalArrayLength = animals.length; for (var i= 0; pos < tamanhoArrayDiagnosticos; ...

computed property failing to retrieve data that was set during initialization

I have a question regarding the timing of computed property execution in the Vue lifecycle. Let's imagine I have a method that I call within the created() hook like this: created () { getSomething() } Within the getSomething() method, I fetch data ...

What is the best way to remove an item from an array inside another object in JavaScript?

I am currently developing an application using Node, mongoose, and express. My goal is to remove an object from an array that is nested inside another object. Here is the structure of the objects: const oldSection = { _id: '62d3f1d221aa21a03fe3bc21& ...