Upon exiting the page, save the initial array in storage. However, the back button will load the last committed array

Currently, I have a feature on my website where users can filter articles based on their category. When the user selects the "ideas" filter, it creates a new array called "ideasFiltered" and stores it in the "filteredArticles" state. This works perfectly when navigating back to the page using the browser's back button. However, if a user goes to another page on the website and then returns to the news page, the previously filtered list is still displayed. Is there a way to only save this filtered data when returning using the back button or from an article page?

Below is my Vuex store setup:

const store = new Vuex.Store({
   state: {
     filteredArticles: this.articles
   },
   mutations: {
     setFilteredList (state, value) {
       state.filteredArticles = value
     }
   },
   plugins: [
     createPersistedState()
   ]
})

Computed property for filtering:

computed: {
  filteredArticles () {
     return store.state.filteredArticles
  }
}

Here's an example of the script that runs when the "ideas" filter is selected:

ideas: function ideas() {
  this.$store.commit('setFilteredList', articles) **// resetting to the full list before filtering**

  var ideasFiltered = this.filteredArticles.filter(function(post) {
     return post.category === 'Ideas';
  });

  this.filteredCategory = 'ideas'; **// used to update the URL with the category**

  this.$store.commit('setFilteredList', ideasFiltered) **// committing the filtered list to the store**
}

Lastly, here is the HTML structure for displaying the articles:

<div class="news-article-list">
  <ul>
     <li v-for="(article, index) in filteredArticles" :key="index">
       <a :href="article.url">
         <img :src="article.featureImg" v-if="article.featureImg" alt="Article Feature Image" />
         <h2 class="news-title">{{ article.title }}</h2>
         <p class="news-date">{{ article.date }}</p>
         <p class="short-desc">{{ article.shortDesc }}...</p>
       </a>
       <router-link class="read-more" :to="article.url">Read More</router-link>
     </li>
  </ul>
</div>

If further explanation is needed, feel free to ask. I want to ensure that all articles are displayed when navigating to different pages but retain the filtered list when going back from an article.

Thank you in advance!

Answer №1

If you're concerned about detecting the back button, I suggest focusing on where the user came from and where they intend to go. These routes, represented by to and from, are crucial for your application. The data in ideasFiltered is persistently altered unless manually cleared. To manage this process, consider creating an action within vue-router that resets the information in ideasFiltered, and then triggering that action based on the user's current route. You can monitor changes to the global vue-router $router by implementing a watch function in your Vue component. In Vue.js 3, the code snippet might look like this:

import {useRoute} from 'vue-router';
import {useStore} from 'vuex';
....

setup() {
const $route = useRoute();
const $store = useStore();
  watch(() => $route.name, async () => {
// Reset filtered list if user is not on News or Articles route
    if ($route.name !=== "News" || $route.name !=== "Articles") {
      $store.dispatch('clearFilteredList', null) // Remember to define this action in your store
    },
    {
      deep: true,
      immediate: true
    }
)
}

To implement the necessary mutation and action in your $store, you could utilize something along these lines:

mutations: {
   setFilteredList (state, value) { // Pass a null value here
     state.filteredArticles = value
   }
actions: {
    clearFilteredList({commit}, payload) { // Ensure payload is null when called from Vue component!
    commit('setFilteredList', payload) // Sets the value to null
}

Keep in mind that the above solution is based on limited information regarding your store code, but it should provide a helpful framework for addressing the issue at hand. Feel free to adjust the use of null as needed - you may opt for an empty array or object instead, such as [].

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

Navigating an array to link values to anchor tags

I'm struggling with an array that contains image file names ["1352.jpg", "1353.jpg", "1354"]. My goal is to loop through this array and generate anchor links for each item separated by commas. I've attempted the following code snippet, but it&apo ...

Ways to retrieve targeted keyframes using JavaScript

Trying to access a scoped "keyframes" named move-left in JavaScript. How can I do this while keeping it scoped? Note that vue-loader will add a random hash to move-left, such as move-left-xxxxxxxxx. <template> <div :style="{animation: animati ...

Does Virtual DOM speed up or slow down applications?

After reading through the Svelte JS documentation, I noticed that one of its advantages is the absence of a Virtual DOM, making apps built with this framework faster and lighter. However, conflicting information suggests that having a Virtual DOM can act ...

Why are the variables not reflecting the changes when an event is triggered?

I'm a beginner in programming and would really appreciate some guidance. Why are my variables not updating when I click the button?? Here is the HTML code snippet: <h1>NIM</h1> <p>Welcome to a simple edition of the game NIM</p& ...

Pressing the space bar invokes an href using AngularJS (ui-router)

How can I handle the space bar key event in Angular? Here are some possible solutions: ng-keyup="$event.keyCode == 32 ? '/settings' : null" ng-keyup="$event.keyCode == 32 ? '#/settings' : null" ng-keyup="$event.keyCode == 32 ? $eval( ...

The function is not explicitly declared within the instance, yet it is being cited during the rendering process in a .vue

import PageNav from '@/components/PageNav.vue'; import PageFooter from '@/components/PageFooter.vue'; export default { name: 'Groups', components: { PageNav, PageFooter, }, data() { return { groups: ...

Transform an array containing objects for convenient manipulation

I am attempting to manipulate an array using parse, push, and save data commands, but it seems like the code is not working properly. Can anyone offer assistance? I am very new to programming and just trying to improve my skills. The array should contain ...

Managing actions with IconMenu and ListItem in React using MaterialUi

Currently, I am delving into the world of React and attempting to create a simple TODO list using Material-UI. However, I have encountered an issue with handling IconMenu menu actions within a listItem element. I am struggling with triggering the deleteI ...

What are the best practices for enabling localization in my Laravel and Vue project while utilizing Inertia?

My expertise lies in intermediate level Laravel development, with several successful projects completed for clients using the framework. Recently, I embarked on a new project involving Laravel with Vue and Inertia, utilizing a starter kit that includes Lar ...

Deleting tasks from the to-do list using Node.js and Express with EJS

Looking to implement functionality where each list item can be removed from a Node.js array by clicking on an HTML button using EJS and Express: I am considering placing an HTML button next to each list element so that the selected element can be removed ...

Enforcement of Typescript Field Type Lax During Assignment

My current issue involves a constructor that is supposed to set the value of _device. The field is specifically designed to be of type number, and the constructor parameter is also expected to be of type number. However, when a parameter of type string is ...

Attempting to create a button that will only appear for items with a defined value for a specific variable

I am currently facing an issue with a template that needs proper population. The store locator on my website lists pharmacies and displays their relevant information (phone number, address, hours of operation) along with three buttons (view store, view fl ...

Retrieve all information from a JSON array

Encountering a minor issue with a basic task. Here is the code snippet in question: JavaScript code Currently able to access the first object element, however, I require all the data objects. I suspect that a modification is needed in this particular cod ...

Dynamic Menu Navigation (No Bootstrap Required)

My Navbar is working perfectly in the original mode but when the screen width is less than 950px, it displays the buttons stacked vertically. However, the dropdown button opens the dropdown content on the wrong side. I want the dropdown content to appear u ...

Summing up various results from promises [Protractor]

On my webpage, I have set up two input text boxes and a label. My aim is to extract the numbers from these elements, sum up the numbers in the text boxes, and then compare the total with the number in the label. Does anyone know how I can achieve this? He ...

Verifying the presence of an ID within a jquery cookie

I encountered an issue with this code on a product page. Whenever I click the save button, it stores the product ID in a jQuery cookie. The IDs are stored in the cookie like this: 1,2,3,4... If an ID is already in the cookie, there seems to be a problem a ...

Implementing the rendering of HTML stored in an array in Angular

I have an array that includes an object with HTML elements which I would like to render in Angular. Here is the array: { name: "rules", key: "rules", value_before: "<tr><td>revisit_in_some_days</td><td>less_then</td>td> ...

JavaScript issue: Submitting form does not trigger the associated function

I am currently in the process of learning JavaScript as part of my university course, and I have encountered an issue where my function is not being called. I am seeking to gain a better understanding of why this problem is occurring. Summary The situati ...

Initially Missing Child Props in Parent Component

I am currently working on an application that utilizes a nutrition API to fetch information such as calories and more. One of the key features I am developing is the ability for users to set their daily calorie target along with the percentage breakdown fo ...

JavaScript nested function "invalid function"

Recently, I've encountered an issue with a JavaScript file that I'm including on my page. Here's a summary of the situation: var PageTransitions = (function() { function setCurrent(currentSet) { alert(currentSet); } fu ...