Tips on destructuring an object property from a Pinia getter that may return an object based on a condition

I obtained this particular Store:

export const useMyStore = defineStore('myStore', {
  state: () => {
    return {
      openTransOnly: false,
      keyword: '',
      openTransStatus: { nextPage: 0, complete: false },
      pastDueTransStatus: { nextPage: 0, complete: false },
    };
  },

  getters: {
    transStatus(state) {
      return state.openTransOnly ? state.openTransStatus : state.pastDueTransStatus;
    },
  },
});

Now let's suppose I wish to transform the "keyword" attribute above into a Ref. Here is how I accomplished that:

const myStore = useMyStore();
const { keyword: needle } = storeToRefs(myStore);

In addition, there is a computed property in my component:

const page = computed({
  get: () => myStore.transStatus.nextPage,
  set: (value) => (myStore.transStatus.nextPage = value),
});

which functions properly. Yet, I am interested in learning how to utilize the same "storeToRefs" used earlier to define the "page". I attempted the following:

const { keyword: needle, transStatus: { nextPage: page } } = storeToRefs(myStore);

However, it returns "page is undefined". What mistake am I making? Is this concept feasible?

Answer №1

The function storeToRefs is designed to return references. It's important to note that transStatus itself is a reference and does not directly contain the property nextPage; instead, it can be accessed via transStatus.value.nextPage. Attempting to destructure nextPage prematurely could result in loss of reactivity due to the nature of transStatus being scalar.

If this scenario arises frequently, the store can implement a computed property called page. Since state mutation should only occur within the store, page can be linked with the setPage action for proper management.

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

When utilizing a React styled component, it functions smoothly during development but triggers a build error when in production

Recently, I encountered a strange issue with my code. I have a styled component div that wraps around another component in this manner: <ContentWidget> <BookDay /> </ContentWidget> (The Bookday component returns an empty div so there ...

Problem with targeting the .prev() and closest() class of a text input box

Could you please review This Demo and advise why I am unable to select the first .fa class before the text box #name ? This is what I have been trying: $(this).prev().closest(".fa").addClass("err"); within this code block <div class="row"> & ...

Caution: Anticipated the server's HTML to include a corresponding <body> within a <div> tag

Upon checking the console, I noticed a warning message appearing. I am puzzled as to why this is happening since I have two matching <body> tags in my index.js file. The complete warning message reads: Warning: Expected server HTML to contain a matc ...

Unable to retrieve variable from ajax success function in response

In my MVC view, I have an ajax call that triggers a chain of 5 functions before completion. Each function contains an if/else statement to return its own error message in case of failure, requiring the original page to be reloaded to display the errors. Ho ...

What is the best way to change the location of a jQuery Mobile global popup?

I have a jQuery Mobile global popup that is initially empty and generated dynamically. I am utilizing the beforeposition event to detect when the popup opens. At this point, I load a configuration file or content file, create the content, and then add it t ...

What is the best way to update the text within a Span element as the user moves through the Jquery slider?

Can I utilize jQquery to dynamically alter the text content of my "video_box_label" span element based on the active slide in my "flexslider" slideshow? For instance, when the slideshow transitions to the second slide, I want the text to change from "Mee ...

Prevent child div from resizing along with parent div during a resize event by utilizing the .resizable()

Check out this example here I am able to resize the div using jQuery, but I don't want the #spacer to have a fixed width at first because the content of the could vary in size. Even if I remove: width:100px; and try setting it to a percentage or ...

Sending data from a child component to its parent counterpart

A component called cartComponent has a data property named cartCount which increases every time a new item is added to the cart. I want to utilize this value to update another value in the template that is not part of the component. Is it achievable? Bel ...

Transform specific data binding values into JSON format using Knockout.js

Just dipping my toes into the world of knockoutjs, I've got this viewmodel set up: var Testing = function(){ this.Username = ko.observable(""); this.Password = ko.observable(""); this.email = ko.observable(""); } I'm tasked with ...

The error message thrown by React JS webpack is "Module not found: Error: Unable to resolve 'src/content/Login/LoginAuthentication'"

Currently working with web "webpack" version "^5.74.0" for my React js project. During the npm start command, webpack is throwing the following error: ERROR in ./src/layouts/SidebarLayout/Sidebar/SidebarMenu/items.ts 21:0-83 Module not ...

AngularJS - Unchecked radio button issue

Within my code, there is an ng-repeat including several radio buttons: <div class="panel panel-default" ng-repeat="item in vm.itemList"> ... <td ng-show="item.edit"> <div class="row"> ...

Acquiring the input from a text box to generate a hyperlink on the current page

I am trying to generate a link that has the href attribute as follows: app\process?val=12000 The catch is that the value for the val parameter (in this case 12000) needs to be derived from a textbox on the page. I am aware that I can retrieve the ...

Unable to play video using the play() method in Video.js player instance

I am trying to start playing a video.js player instance programmatically by using the play() method on it. The markup for the player is as follows: <video-js id ="some-player-id" src ="https://vjs.zencdn.net/v/oceans.mp4&quo ...

What is the best way to choose a single item from an array using jQuery?

Within an array, I have IDs and descriptions like: var tablica = [{"3":"asdasd asd"},{"19":"asddas fff"},{"111111":"adas asf asdff ff"},{"4":"re"},{"5":"asdasd"},{"6":"we"},{"7":"asdasdgg"},{"9":"asdasdasd"},{"16":"sdads"},{"10":"asdgg"},{"11":"ggg"}]; ...

Error: NodeJS is unable to access the property 'name' because it is undefined

I've recently delved into the world of NodeJS with the aim of creating a backend API for a car rental agency. I'm puzzled as to why I'm encountering an error even though I have specified 'name' as a string type and ensured that the ...

The Ionic Capacitor "PushNotifications" plugin is currently not supported on Android devices

I'm encountering an issue while attempting to request permissions using the @capacitor/push-notifications plugin. I have carefully followed all the steps outlined in the README and am working with Ionic and Vue 3. Here is a snippet from my package.js ...

Experiencing the power of DoJo with the latest Wordpress 4

SOLUTION: After some investigation, I discovered that reordering the loading sequence of jQuery UI and DoJo files in the footer resolved the issue. By placing jQuery UI before any DoJo-related files, I ensured jQuery UI was fully loaded before any DoJo scr ...

Having trouble populating the input text field with the selected value from a dropdown using JavaScript

I have implemented a JavaScript function to retrieve the id of a dropdown select with id='odrid'. The script looks like this: $('#odrid').change(function(){ $.getJSON( 'fetch.php', 'odrid='+$(&ap ...

Issues with zDepth functionality in Material-UI (React.js) not being functional

Can anyone explain the concept of zDepth to me? I have a component with the following render method: render() { return ( <div> <AppBar zDepth={2} title="Some title" iconElementLeft={<IconButton onClick={this ...

Ways to select a checkbox in Vue.js?

Is there a way to calculate the total score by toggling checkboxes in Vue.js? I'm having trouble deducting from the total score when the same checkbox is clicked. <template> <div class="container"> <ul class="list-group" v-for="( ...