How can I retrieve my array state in a different router page using VUEJS and VUEX?

I have created a page with two routes - one for the home page and another for the configuration where users can decide what content should be displayed on that container. In the configuration panel, I was able to retrieve input values and stored them in my state using map actions, resulting in an array of string values.

Now, how do I access this array using mapGetters? Here is the snippet of my code:

<template>
  <body>
    <div class="container">
      <h1 v-show="elementVisible" class="info"gt;{{ message }}</h1>
    </div>
  </body>
</template>

<script>
  import moment from "moment";
  import { mapGetters } from "vuex";

  export default {
    name: "Home",
    data() {
      return {
        // message: this.store.state.message
        elementVisible: true
      };
    },
    computed: {
      ...mapGetters(["message", "sec"]),

      ...mapGetters({
        message: "message",
        sec: "sec"
      }),
      createdDate() {
        return moment().format("DD-MM-YYYY");
      },
      createdHours() {
        return moment().format("HH:mm");
      }
    },
    mounted() {
      this.$store.dispatch("SET_MESSAGE");
      this.$store.dispatch("SET_SEC");

      setTimeout(() => (this.elementVisible = false), this.sec);
    }
  };
</script>

My goal is to display the message received from the configuration panel as a clean string within the {{message}} template. The message is currently stored in my state as an array of strings like ["hello", "how are you"]. How can I extract the first value ("hello") and prevent it from being displayed as ["hello"]?

(At present, the entire array is being displayed in the template)

Should I make some changes in my store.js file?

const state = {
  message: [],
  sec: +[]
};
const getters = {
  message: state => {
    return state.message;
  },

  sec: state => {
    return state.sec;
  }
};

const actions = {
  setMessage: ({ commit, state }, inputs) => {
    commit(
      "SET_MESSAGE",
      inputs.map(input => input.message)
    );

    return state.message;
  },

  setSec: ({ commit, state }, inputs) => {
    commit("SET_TIMEOUT", inputs.map(x => x.sec).map(Number));
    console.log(inputs.map(x => x.sec).map(Number));
    return state.sec;
  }
};
const mutations = {
  SET_MESSAGE: (state, newValue) => {
    state.message = newValue;
  },

  SET_TIMEOUT: (state, newSecVal) => {
    state.sec = newSecVal;
  }
};

export default {
  state,
  getters,
  actions,
  mutations
};

The homepage should display the message and handle the timeout functionality based on the sec value provided. It should continue displaying subsequent values from the array after each timeout duration.

Thank you!

Answer №1

Greetings and salutations on Stack Overflow! The message Array is being properly mapped with mapGetters, but it appears that you are flattening it as a String when inserting it into the template using {{message}}. Due to how template interpolation works, objects are converted to strings, similar to calling Array.toString in this context. To properly display the array elements, you need to iterate through them by utilizing the v-for directive:

<template>
  <body>
    <div class="container">
      <h1 v-show="elementVisible" class="info">
        <span v-for="m of message" :key="m">{{m}}</span>
      </h1>
    </div>
  </body>
</template>

If you only require display of the first item, you can directly show it using the following approach:

<template>
  <body>
    <div class="container">
      <h1 v-show="elementVisible" class="info">{{message[0] || 'No message'}}</h1>
    </div>
  </body>
</template>

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

Terminate the JWT token and automatically log out the user in the event of a banning or modification

Greetings fellow developers, I've been working on enhancing my application's user system to include functionality for administrators to upgrade an account's level (granting admin privileges if it reaches level 10) or ban users from the site ...

Guide on integrating AJAX with servlets and JSP for database-driven applications

What is the best way to integrate AJAX technology with servlets and JSP for a database application? I am currently developing a JSP page that makes calls to JavaScript. The JavaScript then calls a servlet where the database is accessed. How can I pass th ...

Create visual representations using the data displayed in charts generated by Chart JS

Good evening. I am currently utilizing Chart JS in my project to visualize the total count per column in a bar graph. My backend framework is Laravel, and I pass the data from the controller using the variable $datacount. This snippet shows the query in ...

Is it possible to apply capitalization or convert the value of props to uppercase in React?

Despite attempting the toUpperCase method, I am unable to capitalize my props value. Here's the code I have: export default function Navbar(props) { return ( <> <div> <nav class="navbar navbar-expand-lg bg-b ...

The response parser in Angular 7 is failing to function correctly

Hey, I recently updated my Angular from version 4.4 to the latest 7 and after encountering several errors, I was able to get my service up and running. However, I'm facing an issue with my output parser function which is supposed to parse the login re ...

Is it possible to detect a specific string being typed by the user in jQuery?

Similar to the way Facebook reacts when you mention a username by typing @username, how can jQuery be used to set up an event listener for [text:1]? I aim to trigger an event when the user types in [text: into a text field. ...

Whenever I include an onClick event to a div element, the entire webpage fails to display

Currently taking on the task of developing a seat booking website. I am encountering an issue with adding an event listener to a particular div element, which should trigger a function to store the value of the div. However, upon implementing the onClick e ...

What is the method for defining the current date variable within a .json object?

When using a post .json method to send an object, I encounter the following situation: { "targetSigningDate": "2021-09-22T21:00:00.000Z" } The "targetSigningDate" always needs to be 'sysdate'. Rather than manually c ...

JavaScript vanilla can be difficult to grasp, especially when it comes to

I'm experiencing a delay in displaying and hiding the mobile menu and table of contents section on my website when viewed on a mobile device. I'm using vanilla JavaScript to add and remove classes, but it's taking about one second for the me ...

Unable to resolve an unresolved issue with a jquery or javascript bug

I am currently facing some issues with my jQuery code in both Firebug and Chrome's developer tools. Any assistance would be greatly appreciated. Kindly make the necessary updates in the provided fiddle. Please follow this link to access the fiddle: ...

Having issues with displaying a pie chart in a React application using Chart.js

I am currently experiencing a problem with displaying a pie chart in a React component using the react-chartjs-2 library and Chart.js. The data for the chart is retrieved from an API, and I expect the chart to appear once the data is ready. However, despit ...

Exploring the differences between UTC and non-UTC date formats in Javascript

When working with JavaScript, I encountered a challenge in comparing two dates that are formatted differently. Specifically: 2015-09-30T00:00:00 and 9/30/2015 12:00:00 AM The former is in UTC format while the latter is not. Despite referring to the same ...

Pattern without anything to duplicate

Could someone help me figure out what I'm doing wrong with this regular expression? I need to create a regex that matches phone numbers in three specific formats: "+38 (093) 937-99-92", "093 937 99 92", and "(093) 937 99 92". As I started working on ...

Top method for independently scrolling overlapping elements in both the x and y directions

Sorry if this is repeating information. I have a structure of nested divs like this: -container -row In order to enable scrolling without the default scrollbar appearing, each container and row has an additional container. My goal is to be able to scrol ...

What is the best way to combine 2 javascript objects to create a JSON structure without any nested levels?

I am having an issue with my mock server setup. I am using npm faker to generate random data, and then trying to transfer that data to another JavaScript file. My goal is to have a JSON structure like the following: { 0: varOne: 'value' ...

Is there a method to access a website, trigger JavaScript functions, and subsequently retrieve the HTML content using PHP?

I am currently exploring options to access a webpage, execute JavaScript functions on it (thus altering the HTML content), and eventually save the modified version of the page. I'm uncertain if this approach is feasible, and if not, are there alternat ...

Ajax: The function assigned to the route does not get executed

Pressing a button triggers a confirmation box. If 'ok' is clicked, the div called 'EventData' should display the word 'reached'. The confirmation box appears when the button is clicked, but 'EventData' does not show ...

"Utilize axios in React to interpret and handle error bodies captured through parsing as a ReadableStream

When I sent a post request using axios in a React form to a PHP server, I encountered an issue where the error returned a ReadableStream in its body. However, when I used Postman, I did not have this problem and received readable errors instead. How can I ...

Using $state outside of the AngularJS environment

Currently, I am working on an AngularJS application that is meant to be a hybrid mobile app for both android and iOS platforms. Within the project, there is a JavaScript file that does not belong to any module. In this particular JavaScript file, I need to ...

Preventing the detection of a jshint "error"

When creating an object using the constructor X, I later add multiple methods in the file using X.prototype.method = function () {...}. Although technically an assignment statement, it behaves like a function declaration, which typically doesn't requi ...