Utilize Vue.js and the vue-datepicker component to store selected date ranges in the centralized global state

I am facing an issue with my datepickers on multiple pages. Every time I choose a date range and navigate to another page, the datepicker inputs reset to their initial state. How can I make the datepickers remember the period I chose across different pages? I think I need to store this information in the global state, but I'm unsure of how to do it.

My datepickers look like this:

<template>
...
<datepicker v-model="periodStart"
                      minimum-view="month"
                      format="MMMM yyyy"/>
          <datepicker v-model="periodEnd"
                      minimum-view="month"
                      format="MMMM yyyy"/>
...
<template>

<script>
...
data() {
return {
  periodStart: new Date(),
  periodEnd: new Date(),
 };
},
methods: {
...mapActions(['loadActiveUsers']),
report() {
  this.loadActiveUsers({ params: {
    start_date: moment(this.periodStart).startOf('month').format('YYYY-MM-DD'),
    end_date: moment(this.periodEnd).endOf('month').format('YYYY-MM-DD'),
    }
   });
  },
},
...
<script>

Here is the Vuex module:

export default {
 state: {
  report: {
    isLoaded: false,
    data: {},
   },
 },
},
...

Answer №1

I'm not sure if you've missed copying some parts of your code.

If you want to interact with the 'report' global object in the Vuex store, you'll need to add the missing functionality:

export default {
    state: {
        report: {
            isLoaded: false,
            data: {},
        },
    },
    actions: {
        setData(context, arr) {
            context.commit('saveData', arr)
        }
    },
    mutations: {
        saveData(state, val) {
            state.report = val
        }
    },
    getters: {
        getReport(state) {
            return state.report
        }
    }
}

In any component, you can access the persistent report object using computed properties like this:

computed: {
            report() {
                return this.$store.getters.getReport
            },
}

This allows you to use {{report}} in your template to display the computed value from the getter function.

To update the global report object with new data from your component, you can use:

this.$store.dispatch('setData', data)

If you're concerned about page refresh when loading a different endpoint, consider using sessionStorage:

Check 'https://caniuse.com/#search=sessionstorage' for browser support and implement a method at the app level using Vue lifecycle hooks (like mounted) to set persistent data to the Vuex model.

For more information on saving JavaScript objects in sessionStorage, visit: Save Javascript objects in sessionStorage

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

Which sorting algorithm is most suitable for handling strings, numbers, or a combination of both in JavaScript?

This situation is quite intriguing to me. Suppose we have an array defined as: var x = [1, 50, 2, 4, 2, 2, 88, 9, 10, 22, 40]; Now, if we run the code x.sort();, it will fail to sort properly. On the other hand, if the array is defined as: var x = ["dog ...

Executing API POST requests by iterating over an array in ECMAScript 6

My dilemma lies in processing an input that follows the format of "ABC, DEF, GHI, ...." The task at hand is to convert this comma-separated list into an array and make a POST request for each value in the array using my API. I'm seeking guidance on t ...

The div element is persisting despite AJAX attempts to remove it

I am currently developing an application that allows users to post and comment. I have a situation where I need to delete a specific comment by clicking on the associated 'x' button. To achieve this, I am making an Ajax call to the remove-comme ...

Is it possible to duplicate the contents of the h1 element to the clipboard?

Hey everyone, I created a translator but it's not perfect. However, it's functional and now I'm looking to enhance it by adding a feature that allows users to copy the result. Is there a way to achieve this? Below is the code snippet I' ...

Tips for recognizing a faulty CSS line in a WordPress site

Recently, I encountered an issue on my website, yildirimakademi, when using woocommerce to add a product to the shopping cart. While the shopping cart logo appears correctly on the right side of the navbar, I noticed that the image becomes distorted when ...

Change an image seamlessly without any flickering, and display the new one instantaneously

TL;DR: How can images be swapped smoothly without causing page flicker while indicating loading status? I am facing an issue with swapping between 2 images using buttons. The first image loads fine, but the second image doesn't display until it' ...

Having trouble converting the JQuery result from the REST request into the correct format

Currently, I am working on making a REST request for an array of objects using JQuery. During the execution of the code within the "success" section, everything works perfectly fine - the objects in the array are converted to the correct type. However, I ...

When I switch to a different page in Django, the item I added to my shopping cart disappears

I'm facing a challenge while developing an e-commerce website using Django. When a product is added to the cart and I navigate to a different page, the product disappears from the shopping cart view. I've added debugging code in my JS file as wel ...

Difficulty encountered with fetching results using jQuery autocomplete with AJAX as the data source

My autocomplete feature is not working properly with my ajax data source. Here is my code: $("#id_q").autocomplete({ source: function (request, response) { $.ajax({ url: "/search/autocomplete/", dataType: "jsonp", ...

Having trouble with validation messages not displaying correctly in Angular after removing a value. What is the correct approach to fix this issue

I've encountered an issue with Angular validation where it's triggering validation on page load, which is not desired. Additionally, when I enter a value, the validation message disappears, but if I return to the textbox and delete the input, the ...

Using Javascript to extract a custom attribute from a button element

In my HTML, there is a button that has a custom property called data-filter-params: <button class="button" type="submit" data-filter-params="{'Type', 'Filter.Type'},{'Code','Filter.Code'}" >Filter</button&g ...

ES6 Generators: lack of informative stack trace when using iterator.throw(err)

The ES6 approach: iterator.throw(err) is often explained as inserting an exception as if it happened at the yield statement within the generator. The challenge lies in the fact that the stack trace of this exception does not include any information about t ...

Capture an image from the webcam without any manual intervention and store it in the system's directories

Looking to automate the process of capturing a picture from a webcam once access is granted, and then saving it without any user intervention. I've managed to capture the image but struggling with: A) Automating the capture process B) Saving the ca ...

The second asynchronous function relies on the completion of the first

Despite dedicating two days to exploring async/await and promises, I am still unable to make it work correctly. The challenge lies in the fact that the second await for b relies on the result of the first a. It seems no matter what approach I take, b keep ...

Teaching you the best way to incorporate numeral.js from app.locals into the script section of my jade file

Encountering issues while trying to utilize numeral.js within the script section of my jade file. Here is how I have numeral placed in locals: app.locals.numeral = require('numeral'); However, when I attempt to use numeral on a variable in my ...

Initializing MongoDB server instance created by NodeJS using npm installation

I've recently installed mongodb on my OSX machine by running the command npm install mongodb in the myapp/node_modules directory while using node.js. However, I'm a bit confused because the mongodb official documentation states that to start mong ...

Struggling with validating forms with JavaScript

I'm having trouble with the following JavaScript code: <script type="text/javascript"> function checkDetails(search) { var search = documment.getElementById('query'); if(search.value ==''||search.val ...

Is the UUID key displayed as an object within a Reactjs prop?

Hey there internet pals, I've stumbled upon a mysterious corridor, so dark that I can't see where I'm going.. could really use someone's flashlight to light the way. I have put together a basic, no-frills to-do list program. It consi ...

Is it possible to have background videos in safari without experiencing any lag?

Currently, I have implemented a background video on my webpage, which features a simple layout where you scroll to view images with a fixed background video. While it works smoothly on Chrome, I have noticed that it appears choppy and laggy on Safari. Are ...

Ways to expose a components prop to its slotted elements

I've set up my structure as follows: <childs> <child> <ul> <li v-for="item in currentData">@{{ item.name }}</li> </ul> </child> </childs> Within the child component, t ...