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

jQuery - Error: Unexpected token SyntaxError

I'm new to jQuery and facing a challenge with an AJAX request. I have a server on my local network running a Python service. When I make a request to the server through the browser using the URL: http://192.168.0.109:5000/api/environment?seconds=10 ...

Find the furthest distance from the average in a set of data points and identify the corresponding data point

Imagine having an array of data structured like this: var data = [{name: "craig", value: 10}, {name: "oliver", value: 15}] My goal is to create a function that can accept parameters like: function findExtremeValue(windowSize, pointsToTake, data, valueAc ...

Choosing an option from the dropdown menu with the help of the incredible HTMX framework

I attempted the provided solution but unfortunately, it did not yield the desired outcome. Upon checking the HTMX log, it appears that everything is set up correctly. Can anyone point out what mistake I might be making in this scenario? document.getElem ...

What are the best ways to expand product rows to their full potential?

I am currently working on a Nuxt.js (Vue.js) application that utilizes the BootstrapVue package. Here is the current setup: https://i.sstatic.net/CuRST.jpg https://i.sstatic.net/D9eCR.png The code snippet is as follows: <template lang="pug" ...

Interact with the horizontal click and drag scroller to navigate through various sections effortlessly, each designed to assist you

Currently, I am facing an issue with my horizontal scrolling feature in JavaScript. It works perfectly for one specific section that has a particular classname, but it fails to replicate the same effects for other sections that share the same classname. ...

How can real-time data be fetched or connected to Firebase v9 in the onSubmit function?

Please provide the code in firebase-v9 to fetch the onSubmit function from firestore: const onSubmit = (formData) => { console.log(formData) db.collection('emails').add({ to: formData.to, subject: formData.subject, message: formData.mess ...

Instructions on utilizing the signUp() function in Supabase for including extra user details during the registration process

My latest project involves building a Vue.js application with authentication using Supabase. I've been trying to implement the signUp() method from Supabase in order to collect extra user data during the sign-up process. In my code, I added a property ...

AngularJS creates a new window in your application

I have created two html pages named web.html and addroute.html. Both pages are built with bootstrap. The angularjs script includes two controllers: webctrl and addctrl. In web.html, there is a button that, when clicked, opens the addroute.html page. I am ...

Generate a configuration file that allows for the reading and storage of modifications

Is there a way to create a configuration file (JSON) on the local file system using JavaScript where I can write and modify data without losing it when the application is restarted? Any suggestions or solutions for this problem? Thank you for your assista ...

What are the different methods for completing a form?

From what I understand, there are 2 methods for submitting a form. For instance, in asp.net, there is the Button.UseSubmitBehavior property which Specifies whether the Button control uses the client browser's submit mechanism or the ASP.NET postb ...

What is the best method for effectively organizing and storing DOM elements alongside their related objects?

In order to efficiently handle key input events for multiple textareas on the page, I have decided to create a TextareaState object to cache information related to each textarea. This includes data such as whether changes have been made and the previous co ...

steps for transferring a shallow copy of an array to a function

How can I adjust this code so that when I press each button, the console.log displays a different slice of the array instead of always showing me the last 20 elements? for (var i = 0; i < array.length; i++) { var b; var NewArr = []; ...

Error message: jQuery AJAX request fails due to permission denial issue on Internet Explorer

I am facing a major challenge on my website. I have implemented AJAX to update the content of a DIV, which works perfectly on all pages except for some links under the Portfolio tab. The links for "photography", "interactive", "print", and "traditional" tr ...

When trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

Which is the best choice for a large-scale production app: caret, tilde, or a fixed package.json

I am currently managing a sizeable react application in production and I find myself undecided on whether it is more beneficial to use fixed versions for my packages. Some suggest that using the caret (^) is a safer route, but I worry that this could poten ...

What is the best approach for incorporating sub-navigation within a page popup in a Next.js project?

In the midst of my Next.js project, there is a requirement to showcase a chat popup consisting of multiple sub-pages like user registration, conversation page, and more. Hence, seamless navigation inside this popup is necessary. The idea is not to alter th ...

What sets Redux React-Native apart: Exploring the nuances between utilizing useSelector in react-redux versus connect

I believe they were identical because both extracted the content from the store. What could potentially differentiate them? ...

Endless [React Native] onFlatList onEndReached callback invoked

Attempting to create my debut app using ReactNative with Expo, I've hit a snag with FlatList. The components are making infinite calls even when I'm not at the end of the view. Another issue might be related; across multiple screens, the infinite ...

How can a particular component within the DOM be referenced and stored for future use?

The issue at hand: My current project involves developing a file tree with a specific feature called "Selected Folder." This functionality allows users to designate a target for creating new files and folders within the tree. (I'm using Vue in Electr ...

Unable to change the filename when utilizing Angular.js ng-file-upload

After uploading a file using Angular.js ng-file-upload, I am attempting to rename the file. However, when I remove the properties ngf-min-height="400" ngf-resize="{width: 400, height:400}", I encounter an issue. Below is my code: <input type="file" dat ...