Sending state information through props in a Vuex environment

One of the challenges I am facing is how to make a reusable component that can display data from the store. My idea is to pass the name of the store module and property name through props, as shown below:

<thingy module="module1" section="person">

Inside the component:

<template>
  <h2>{{ title }}</h2>
  <p>{{ message }}</p>
</template>

<script>
import { mapState } from 'vuex';
import get from 'lodash.get';

export default {
  props: [
    'module',
    'section',
  ],
  computed: mapState(this.module, {
    title: state => get(state, `${this.section}.title`),
    message: state => get(state, `${this.section}.message`),
  })
}
</script>

The issue I'm encountering is that the props are undefined when mapState() runs. If I manually set the prop values, the component works fine. When checking the props in the created() hook, they show the correct values. It seems like there might be a race condition happening.

Could it be that I am approaching this problem in the wrong way?

Update

In order to properly access the module namespace within the mapping function, it needs to be passed as part of the computed object, like so:

computed: mapState({
  title() {
    return get(this.$store.state, `${this.module}.${this.section}.title`);
  },
  message() {
    return get(this.$store.state, `${this.module}.${this.section}.message`);
  }
})

(please note that get() is a lodash function, not a vue method)

This logic can also be moved into a mixin for further abstraction.

Answer №1

In the mapState example, it is noted to use a normal function when accessing local state with `this`:

// to access local state with `this`, a normal function must be used
countPlusLocalState (state) {
  return state.count + this.localCount
}

The usage of arrow functions is highlighted in your implementation.

Regarding this.module, it seems that using the binding helper notation may not work as expected. Instead, you may need to explicitly reference the module in the definitions. This could potentially look like:

computed: mapState(this.module, {
  title(state) {
    return get(`${state}.${this.module}`, `${this.section}.title`);
  },
  message(state) {
    return get(`${state}.${this.module}`, `${this.section}.message`);
  }
})

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

Having trouble accessing data in Laravel and Vue JS views

I'm currently working on displaying table data in a view using Vue.js and Laravel. Here is what I have attempted so far: This is the comment controller: public function index() { $comment = Comment::Latest()->paginate(10); return new Comm ...

Tool to stop automatic logouts on websites

In the web application where I work, users are automatically logged out after a period of inactivity. Unfortunately, I am unable to control this feature. The code responsible for logging the user out is as follows: var windoc = window.document; var timeou ...

The hover effect is not functioning properly after loading jQuery with load();

When loading elements into a div using the load() function, I noticed that the :hover effect in CSS stops working for those elements. It's a dynamic menu setup, as shown below: <div id='main-menu'> <ul> <li class='click ...

Angular update row and save data to an array

When comparing the data of an edited row with the row just below it, I encounter a specific scenario. In a table containing 5 rows, as I edit records from top to bottom using the provided code snippet, I am able to store the values in an array. The most re ...

Utilizing columns within the 'segment' element in Semantic-ui to enhance layout design

I am looking to divide the ui-segment into 3 columns and display the ui-statistics evenly. Below is the code I have used in an attempt to achieve this: <div class="ui container"> <div class="ui segment"> <h3 class="ui header"> ...

Execute JavaScript AJAX Request On Page Load

I am facing an issue with creating an onload event in which an AJAX function needs to be called and passed a value. The challenge lies in the fact that I have both my header and footer split into sections via PHP, therefore I cannot place it on the body ta ...

What is the best way to split text copied from a textarea into <p> paragraphs with an equal number of characters in each?

Check out this JSFiddle version I've found a JSFiddle example that seems perfect for my current project needs. However, I'm wondering how to modify the code to ensure that each paragraph is evenly divided with the same number of characters and a ...

Is Javascript the best choice for managing multiple instances of similar HTML code?

I am currently facing the challenge of dealing with a lengthy HTML page consisting of around 300 lines of code. The majority of the code involves repetitive forms, each identical except for the ID (which varies by number). Is it considered appropriate or ...

The contents of a Javascript array are not appearing within a div element

I have developed a program that reads JSON data related to a concert event. The JSON file consists of an object named global, which includes details about the band name and venue. Additionally, there is a tickets object that contains information on all ava ...

Creating PHP functions that return a JSON string when invoked - a simple guide

I have created a script that contains various functionalities, including fetching data from a database and encoding it into JSON. However, I want to be able to call different functions to execute these scripts separately. When I attempted to define and c ...

Bringing JQuery into your Electron project through HTML

Working on some ElectronJS HTML coding and in need of using JQuery within the HTML. I've gone ahead and installed jQuery with npm install jquery. The question is, which file do I import to make use of JQuery? <!DOCTYPE html> <html lang="en" ...

Leveraging Backbone.js without using client-side JavaScript

Exploring the idea of using Backbone.js and node.js to develop a compact web application. The concept of sharing code between the client and server is quite appealing. The challenge arises when considering how users without JavaScript-enabled browsers (in ...

Guide to center align fields in Ionic and Angular

I am working on creating a login screen that resembles the image provided. I have managed to set the background image, input fields, and buttons successfully. However, I am encountering a few issues: The width of my input field is taking up the entire spa ...

Uncovered event listener in Angular tests

Imagine having a custom directive: angular.module('foo').directive('myDir', function () { return { restrict: 'E', link: function (scope) { var watcher = scope.$watch('foo, function () {}); scope.$on ...

Troubleshooting issue with Next.JS Redux dispatch functionality inside getStaticProps() not functioning as

I have recently started working with Next.JS and decided to integrate Redux into my Next.JS application. I'm facing an issue where my page is supposed to display a list of posts fetched from an API. Everything works fine when I use useEffect() to disp ...

Tips for preventing breaks in typography

I have implemented a material ui Typography component, but it's causing a line break even though there is enough space. Here is the code snippet: <Box flexDirection="row"> <Typography> Gender: <RadioGroup row ...

What steps are involved in verifying the data stored in the database?

I need help setting up authorization in PHP. Although I'm not very familiar with it, I have been tasked with implementing this feature. I want the authorization process to occur when a user clicks on a button and then redirect them to another page. I ...

Requiring addresses for Google Maps in order to display directions

To display the directions between two addresses based on the chosen transportation mode, I need to pass the addresses to the code in page 2. After the user selects two cities from a Dropdown box on page 1, they will be sent to the code to show their locati ...

Dealing with shared content in your Capacitor Android application may require some specific steps

As a beginner in android development, I am currently embarking on my first Capacitor Android app project using Quasar/Vue. My goal is to enable the app to receive files/images shared from other apps. Through research, I have discovered how to register my a ...

Why won't setInterval function properly with innerHTML?

I've been attempting to include a small feature on my website that displays the running seconds, but for some reason my JavaScript function isn't working. Strangely, it's not throwing any errors either. Here's the code I'm using: f ...