Issue with fetching data from Vuex in VueJS doesn't give expected result

I'm currently working on integrating a messaging/alert system using Vuex in my project. The goal is to pass an argument from various components, triggering the display of specific messages through vuex getters. However, I'm facing an issue where no data is being returned.

While I understand that this might be seen as excessive for a simple flash messaging feature, it serves a larger purpose once fully functional.

Currently, I am passing the message key/name to match in the state alertMessages array via the Alert component. Eventually, this will be done through method calls from the Login Component.

Here's the structure:

• App.vue
--> • Alert component
--> • Login component (login method)
--> • NavHeader component
    --> Logout Btn (logout method)
• Store.js

This is what I have in Store.js:

export const store = new Vuex.Store({
   state: {
      alertMessages: [
         { key: "loginSuccess", alert: "logged in.", redirectPath: "dashboard" },
         { key: "loginError", alert: "try again.", redirectPath: "login" }
      ]
   },
   getters: {
      pickMessage: state => {
         return (something) => {
            state.alertMessages.forEach(msg => {
               if(msg.key == something){
                  // The current return does not send any data through.
                  return msg.alert;
               }
            });
            // This return works. Alert gets Hey There.
            // return "Hey There";
         }
      }
   }
});

In Alert.vue:

<template>
   <div class="alert">
       {{message}}
   </div>
</template>

Scripts:

export default {
   name: 'alert',
   data () {
      return {
         message: ''
      }
   },
   computed: {
      alertMessage: async function(){
         try {
            // Passing loginSuccess for key matching.
            this.message = this.$store.getters.pickMessage('loginSuccess');
         } catch(error) {
            console.log(error);
         }
      }
   },
   created: function(){
      this.alertMessage;
   }
}

It seems like the if() statement is causing issues with the return inside it. I can confirm that the function argument from the Alert component is being passed correctly, as I can log it. Can you spot what I may be missing here?

Thank you in advance,

Sergio

Answer №1

According to MDN, the sole method of ending a forEach() loop is by throwing an exception. This limitation results in the issue present in your code snippet above.

Answer №2

After making the adjustment to the getters as shown below, I was able to resolve the issue... What caused my original code to fail? Could it be due to having the return statement within the forEach loop (resulting in multiple returns)?

Code that worked:

   getters: {
      pickMessage: state => {
         return (something) => {
          let val;
            state.alertMessages.forEach(msg => {
               if(msg.key == something){
                 val = msg.alert;
               }
            });
            // The return here is effective. It outputs "Hey There."
            // return "Hey There";

            return val;
         }
      }
   }

UPDATE: A more concise solution involves replacing the forEach loop with a for...of loop – Credit goes to Ujjwal Nepal!!!

Here's an updated code snippet:

getters: {
      pickMessage: state => {
         return (something) => {
            let arr = state.alertMessages
            for(let a of arr){
               if(a.key == something){
                  return a.alert;
               }
            }
         }
      }
   }

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

jQuery failing to recognize clicks on dynamically added element

Here's the scenario: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" ...

Ways to extract the source code of a webpage that has been modified on load

While working on extracting data from a website (completely within legal boundaries), I encountered an interesting situation. This particular site has 5 questions with answers on each page. However, upon inspecting the source code by pressing Ctrl+U, I no ...

How can I use TypeScript to wrap a component in Vue 3?

Looking to customize a PrimeVue component (Calendar) by styling it differently and then re-exporting it. Here's an example in React: const WrappedCalendar: React.FC<CalendarProps> = (props)=> <div style={{background:'green'}}&g ...

Utilize Vue to fetch authenticated Laravel data for populating purposes

Is there a way to fill the auth()->user()->first_name or {{ optional(auth()->user()->first_name) }} in my blade template? Can I use vue.js file.js to populate user.first_name with the code below? var app = new Vue({ el: '#property-boo ...

Can you place a v-snackbar underneath a temporary v-navigation-drawer?

Is it possible to stack the v-navigation-drawer over a v-snackbar with the "temporary" prop enabled? Typically, the snackbar obeys the navigation drawer when the app prop is set, except when the drawer has the temporary prop. While this behavior may make ...

When retrieving data from a PHP $_SESSION using an Ajax $_POST call, outdated information is being returned

I am encountering an issue that I cannot seem to figure out. Currently, my application consists of three pages: Home.php Nearmiss.php Reports.php Each of these pages includes code at the top with a specific "thispage" variable unique to that page. < ...

Troubleshooting PHP and jQuery AJAX: Why is $_POST always empty?

I'm struggling to display the $_POST value in an alert box using jQuery AJAX function. However, the $_POST value from my PHP controller always turns out to be empty, resulting in an empty array in the response. My setup includes PHP version 5.5 and j ...

What is the best way to attach an attribute to a element created dynamically in Angular2+?

After reviewing resources like this and this, I've run into issues trying to set attributes on dynamically generated elements within a custom component (<c-tabs>). Relevant Elements https://i.stack.imgur.com/9HoC2.png HTML <c-tabs #mainCom ...

Accessing node postgres and fetching combined fields with duplicate names

Currently, I am developing a node.js application that utilizes the pg package to connect to a PostgreSQL database. The problem I am encountering involves querying data using a join statement and finding that fields from one table overwrite those from anoth ...

Passing predefined functions to asynchronous functions can be achieved by simply defining the

I am facing a challenge in passing a predefined function within an async function. The piece of code below is functioning flawlessly: async.auto({ getAccessToken: function (callback) { let x = { access_token: signToken({ userId: u ...

Tips for managing the submission process for dynamically generated formsORStrategies for

<tr> <form role="form" class="manualImportSubmit" action="http://localhost:5000/XXX" method="post"> <td><input name="yyy" value="FormAValue" type="hidden">TestA</td> <td><input name="before_year" class="fo ...

The JavaScript .load() function fails to run

Attempting to create a straightforward Newsfeed page based on user interests. Here is the code I have implemented for this purpose. The issue I'm facing is that while the code works fine on my local server, it encounters problems when running on an on ...

Tips for avoiding axios from making a post request before the state is properly updated

I'm encountering an issue where the post request doesn't send the updated currentVideo state because setState appears to be non-blocking. Is there a way to make axios wait for the state to be set before making the post request? const nextVideo = ...

Storing form datepicker data into MongoDB using Node.js

Having an issue with the date formatting between Angular Material 6's Datepicker and Node.js. When displaying the date in the browser, it shows as 06/20/1992, but in the console output, it appears as Sat Jun 20 1992 00:00:00 GMT+0800 (Philippine Stand ...

What is the solution to rectifying the issue with graphql codegen?

Upon running the command "yarn graphql-codegen," an error occurred and I am unsure how to resolve it: % yarn graphql-codegen yarn run v1.22.4 warning package.json: No license field $ /Users/xxx/node_modules/.bin/graphql-codegen ✔ Parse Configuration ⚠ ...

Enhancing the Efficiency of JavaScript's indexOf Method

I am currently developing a basic search algorithm in JavaScript. var title = "Discovering the Best Book of All Time"; var search1 = "of DiscoverinG boOk Best"; var search2 = "Of TIme best all" var search3 = "Book discovering time" When using indexOf(), ...

Navigating with Plone and AngularJS路径

Hello, I'm currently diving into AngularJS and experimenting with building an AngularJS based Plone addon. One challenge I'm facing relates to routing. Let's say I have a Plone URL, like http://localhost/blah/my_page When a user clicks on ...

Conceal additional code within the app.js file specifically within the login section of a Vue application

Currently, I am working on developing an app using a combination of Laravel and Vue. One issue I have encountered is that Vue loads all the JavaScript codes stored in app.js even on the login page, where the user has not yet been authenticated. I would p ...

Eradicating a character from an Object using Jquery/Javascript

Looking at this code snippet, it appears that the 3rd column is not calculating correctly due to a comma being present in one of the values. Is there a way to rectify this issue without directly removing the comma? I am aware that using .replace(/,/g,&apos ...

Personalize Bootstrap 5 slider for mobile (displaying multiple items without being arranged in a single row)

Having trouble customizing the carousel layout for mobile devices. I'm trying to display all items of the carousel on mobile instead of just one. I've been experimenting with CSS and JS, specifically with the display, float, or max-width properti ...