Utilize a method in Vue.js to filter an array within a computed property

I have a question regarding my computed property setup. I want to filter the list of courses displayed when a user clicks a button that triggers the courseFilters() method, showing only non-archived courses.

Below is my current computed property implementation:

filterCourses() {
            const getUser = this.$store.getters['UserData/getUser']
            
            return this.courses.filter((item) => {
                if(this.checkAuthorization(['leader'])) {
                    return item.createdBy === getUser.uid
                } else {
                    return item
                }
            })
        }

And here is the courseFilters method in my code:

courseFilters(which) {
        if(which == 'hide-archived') {
            this.filterCourses.filter((item) => {
                if(!item.archive) {
                    return item
                }
            })
        }
        if(which == 'clear') {
            this.getCourses(this.$store.getters['AppData/cid'])
        }
    }

However, when I click the button to apply the filters, nothing happens to the computed property output.

Answer №1

It seems like there may be some confusion regarding the specifics of your issue, but I have outlined a potential solution below that could serve as inspiration:

export default {
  data() {
    return { showArchivedCourses: false };
  },
  computed: {
    accessibleCourses() {
      const user = this.$store.getters['UserData/getUser'];

      // The filter callback should return true or false.
      // If your current code is functioning correctly, you can skip this section.
      return this.courses.filter(
        (c) => this.checkAuthorization(['leader']) && c.createdBy === user.uid
      );
    },
    visibleCourses() {
      // This will determine which courses to display in your template.
      // It will either show all authorized courses or only those that are not archived.
      return this.showArchivedCourses
        ? this.accessibleCourses
        : this.accessibleCourses.filter((c) => !c.archive);
    },
  },
  methods: {
    toggleVisibility() {
      // Toggles between displaying and hiding archived courses
      this.showArchivedCourses = !this.showArchivedCourses;
    },
  },
};

This component manages the state for showing or hiding archived courses through a toggling method. By utilizing computed properties effectively, you can obtain the desired output based on the current state. In addition, note that I have named the computed properties with nouns rather than verbs for improved code comprehension.

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

Transfer data from distinct arrays to separate variables

I have 2 arrays structured like this: let dataA = [{"id": "a1", "name": "Alpha"}, {"id": "a2", "name": "Beta"}, {"id": "a3", "name": "Gamma&quo ...

Leverage the version attribute within package.json within one of its scripts

Is there a way to access the version attribute of my package.json file within one of its scripts? I want to include the version number in the name of the JS bundle, instead of using a hash as an identifier. This is what I currently have: "build-js": "bro ...

Contrasts in the immutability strategies of Vuex and Redux

After exploring Vuex and noticing how simple it is to mutate states with mutation handlers using basic assignment, I am currently delving into redux. I have come to realize that redux emphasizes immutability, which can make coding a bit more verbose. This ...

I'm having trouble pinpointing the cause of the never-ending loop in this React code that is using Material UI grid

There seems to be an issue with infinite looping in this code, and I can't figure out the cause, import React, { useEffect, useState } from 'react'; import VideoCardComponent from './VideoCard'; import Grid from '@mui/material ...

What is the best way to convert a string in JavaScript to be case-insensitive?

Can anyone assist me? Challenge: Develop a function called indexOfIgnoreCase which takes in two strings and identifies the first instance of the second string within the first string. This function should be insensitive to letter case. For example, indexO ...

wiping out a column in Excel spreadsheets with the help of Node.js or its corresponding node modules

I've attempted various approaches without success. Can you provide guidance on deleting and adding columns within an Excel sheet using Node.js? ...

The DOM assigned a new source to an image

Currently, I am working on a project that involves both jquery and PHP. In this project, users are able to upload images which are then displayed in blocks. The uploading functionality is already working, but I am facing an issue with setting the image sou ...

Navigate to a different HTML file following a JavaScript function in Ionic and AngularJS with Cordova

I am currently creating an Android application in Cordova Tools for Visual Studio using Ionic and AngularJS. My goal is to redirect to another HTML page once my function has completed its execution, but I'm having trouble getting it to work correctly ...

Scrolling automatically within a child element that has a maximum height limit

I am currently developing a console/terminal feature for my website. https://i.stack.imgur.com/AEFNF.jpg My objective is to allow users to input commands and receive output, which might consist of multiple lines of information. When new output is displa ...

Getting Values from .Properties File in JavaScript/HTML pages that are Executing in a Node.js Server

I have a configuration file named "site.properties" with the following content: #Properties file #Database Connection Info db.host.name = localhost db.user.name = username db.password = password db.database.schema = db1 #Server Connection Info ...

Updating the DOM does not occur by simply adding an object to the Array; instead, the database is updated once the data has

My database has verified data that is being updated, however, the DOM is not reflecting these updates. <ul> <li ng-repeat="aReview in reviewList"> .... .... </li> </ul> <script> if(globalMethods.stringVa ...

Struggling with registering a property in the App.vue component

Forgive me for asking such a silly question, but despite my best efforts with the documentation, I am struggling to grasp how this works. I'm attempting to configure a basic property in App.vue and encountering an error: The property or method "te ...

The implementation of a universal translation system in Express JS

I have developed a straightforward translation module for Express JS. It exists as a global object in the application scope and is initialized during application runtime: translator.configure({ translations: 'translations.json' }); I have i ...

Develop a unique method for loading AngularJS templates

When working with AngularJS, there are various ways to provide an external template, such as using a script tag or a separate HTML file on the web server. However, I am faced with a situation where I need to implement a custom logic for retrieving these ...

Dealing with ReactJs Unhandled Promise Rejection: SyntaxError - Here's the Solution

Struggling to use the Fetch API in ReactJS to retrieve a list of movies. Encountering an issue, can anyone offer assistance? fetch("https://reactnative.dev/movies.json", { mode: "no-cors", // 'cors' by default }) ...

Determine which scroll bar is currently in use

I'm running into an issue with multiple scrollbars on my page - they just don't seem to be functioning correctly: <div class="dates-container" v-for="id in ids"> <overlay-scrollbars :ref="`datesHeader` ...

What is the most effective method for retrieving a key and value from an Axios response object?

I currently have a Mongoose schema set up to store key:value pairs in a mixed type array, represented like this: Mongoose const budgetSchema = new Schema({ earnings: Number, expenses: [mongoose.Schema.Types.Mixed] }); budget:{ earning:1000, exp ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

It requires two clicks on the button for the Vue and Pinia store to update

I've been experimenting with Vue and trying to understand it better. When I click the button in LoginForm.vue for the first time, both token and user_data are null. It's only on the second click that they finally update. How can I ensure these va ...

Encountering a 403 error while attempting to install Meteor with npm using the command npm install -

Following the installation instructions provided on the official Meteor website at , I encountered an error while trying to install Meteor using the command "npm install -g meteor". Here is the detailed error message: os  win 10 pro node -v  v14.15.1 n ...