I'm curious about how to distinguish the function responsible for changing state when combining Vue3's composition api with vuex

<!-- ChooseColor.vue -->
<script setup>
import { defineProps } from "vue";
import { useStore } from "vuex";
import { storeData } from "./common";

let { resultColor } = storeData();
const props = defineProps({
  selectType: String,
});
const store = useStore();
const updateSelection = (e) => {
  store.commit("resultColor/updateResultColor", {
    type: props.selectType,
    value: e.target.value,
  });
};
const isSelectedOption = (type) => {
  return props.selectType == type;
};
</script>

I have organized the code above to access the store state separately and store it in a different file.

//common.js
import { computed, reactive, toRefs } from "vue";
import { useStore } from "vuex";

const storeData = () => {
  const store = useStore();
  let state = reactive({
    count: computed(() => store.state.count.count),
    resultColor: computed(() => store.state.resultColor.resultColor),
    resultList: computed(() => store.state.count.result),
  });
  return toRefs(state);
};

export { storeData };

By following this approach, I aim to streamline this part of the code.↓

const store = useStore();
const updateSelection = (e) => {
  store.commit("resultColor/updateResultColor", {
    type: props.selectType,
    value: e.target.value,
  });
};

I am looking for a way to avoid repetitive use of the useStore function. Is there any solution for this?

Answer №1

When using composable use functions, it is important to use them directly within the setup function or at the top level of the tag when using <script setup>. The specifics of where these functions can be used may vary depending on the implementation and should be verified.

The useStore function is typically used only once per component:

import { useStore } from "vuex";

const store = useStore();
...

If the code is not located inside a component, the store can be imported directly as shown below:

import store from '...';

In situations where constant restructuring of the storeData is necessary, it may indicate an XY problem stemming from an incorrectly designed store. Instead, consider using a reactive object for the state within the store, which would provide access to up-to-date store data without constantly restructuring.

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

How to create dynamic options in a select dropdown based on the selection of another dropdown using HTML, JavaScript, or PHP

There are two dropdown menus here. <select name="firstdropdown" id="firstDropdown"> <option value="choiceOne">Choice One</option> <option value="choiceTwo">Choice Two</option> </select> <select name="seconddropdown ...

Determine in Javascript if a timestamp is within the last 24 hours or not

I'm looking to access Bitbucket repositories and refine them based on the updated_on timestamp. TARGET: The aim is to narrow down the ones that were updated within the last 24 hours. This is the information retrieved from the API: updated_on: 2018-0 ...

Using JavaScript onChange event with ModelChoiceField arguments

In my Django project, I have a Students model with various fields. I created a ModelChoiceField form allowing users to select a record from the Students table via a dropdown. forms.py: class StudentChoiceField(forms.Form): students = forms.ModelChoic ...

What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu If the status for sorting and filtering is true, how do I proceed? const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, ...

Experiencing H12 and 503 errors while using the Heroku server

Every time I attempt to make a POST request on my Heroku app, I encounter a 503 error. Strangely enough, the functionality works perfectly fine when running the app locally. at=error code=H12 desc="Request timeout" method=POST path="/login" host=classes-t ...

Navigating spaces, tabs, and line breaks during ReactJS rendering

I have been attempting to display a string in a ReactJS Dialog box, which contains spaces and newlines represented by /n /t characters. My goal is to show the text exactly as it is with all the spaces and line breaks preserved. Despite trying various metho ...

Animating with JQuery utilizing a dynamic attribute

We are facing a challenge with animating multiple divs that share the same class name and have different attribute values: <div class="chart-bar" style="width:10%;" bar-width="100%"></div> <div class="chart-bar" style="width:10%;" bar-wid ...

Display images in a rating system using Angular's ng-repeat directive

Need help with modifying star images based on ratings? I have two PNG files, one with an empty star and one with a full star. My goal is to dynamically adjust the number of stars displayed depending on the rating given, which ranges from 1 to 5. However, m ...

Different Option for Anchor Tag When Javascript is Disabled

One interesting feature is the ability to set a different "href" attribute for an anchor tag when JavaScript is disabled. For instance: When JavaScript is enabled: <a href="#news">News</a> If JavaScript is not enabled: <a href="news.htm ...

Tips for displaying HTML tags in a chatbot using JavaScript or jQuery

I'm currently working on revamping an older chatbot project I stumbled upon online. It serves as a basic "command bot" that provides specific responses based on user input. However, the chatbot is mainly text-based and does not support rendering HTML ...

Facing difficulties in displaying a variable on the screen in AngularJS?

I am struggling with a small controller and some basic data in my code. When I click the link, my messages are not showing up as expected. Surprisingly, there are no errors in the console and when I check the variables, they do show up. However, for some r ...

Using Angular2 to Inject a Service into Another Service

I'm having trouble locating my mistake. app.module.ts ... providers: [ValidateService,AuthService] ... In the register.component.ts file, I perform the following actions: import {AuthService} from '../../services/auth.service' ...

Navigating through layers of JSON arrays in Node.js

Struggling to remove the 'id' key from a JSON object, managed to delete it from the root level but facing issues when trying to eliminate nested 'id' keys within arrays. Check out the code snippet below: var json = { "id" : "a28b469b-b ...

Learning to Use jQuery to Send JSON Requests in Rails

I am attempting to send a JSON post request to a Rails 3 server. Here is the AJAX request I have set up: $.ajax({ type: 'POST',<br> contentType: "application/json",<br> url: url, ...

Error: Koa.js framework is unable to find the "users" relation in the Sequelize database

I am currently facing an issue while attempting to establish a relationship between two tables, 'user' and 'accessToken'. The error message I am encountering is hindering the process. Below are the models in question:- User model:- ...

Adding buttons dynamically using jQuery

I am currently working on a project where I need to dynamically generate additional buttons to provide more options. However, when I click the "more options" button, only one button is added each time. My goal is for it to display three buttons and connect ...

The plugin "react" encountered a conflict while trying to sync with both the "package.json" and the "BaseConfig" files

Whenever I open Terminal in my react folder and try to start the react app using npm start, I always end up encountering an error on the browser. The error message states that the "react" plugin is conflicting between two paths: "package.json » eslint ...

In Node.js and Express, it is important to note that a variable must be declared before

When I use the express action get('items'), I encounter an issue while trying to call an external JSON-API and display the API response in my local response. The error that I am currently facing states that the items variable is not defined with ...

How can I insert a variable into the URL for fetching data in React?

Here's a fetch request I have: fetch(`https://example/e1/e11/${variable1}?param=A1&include=metadata`, { "method": "GET"... Is there an issue with declaring the variable1 in this manner? It seems to work fine when written lik ...

Implementing global parameters in ui-router

Currently, I am utilizing ui-router in AngularJS as shown below: .state ('browse.category', { url: "/:category", templateUrl: "views/browseCategory.html", controller: function($stateParams, $scope) { $scope.params = $st ...