"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter.

I initialized a store with a list under state (pages)

// state.js
const state = {
  pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}]
};

In my getter, I tried implementing a find method similar to what was discussed in this post: Reference

// getters.js
const getters = {
  indexPage: state => {
    let indexPage = state.pages.find(function(page) { // encountered the same issue with arrow function
      return page.id === 1;
    });
    return indexPage !== undefined ? indexPage : null;
  }
}

I expected to retrieve the first object but upon mapping the getter (using mapGetters) in a component, it led to the following error:

TypeError: "page is undefined"

In an attempt to resolve this issue, I also experimented with the .filter() method (which returns an array). Surprisingly, it worked flawlessly without any errors. The modified code snippet looks like this:

const getters = {
  indexPage: state => {
    let indexPage = state.pages.filter(page => page.id === 1);
    return indexPage[0];
  }
}

Answer №1

Give this a shot:

const getters = {
  indexPage: state => page => state.pages.find(p => p.id === page)
}

UPDATE: try using mapGetters

const store = new Vuex.Store({
  state: {
    pages: [
      {id:1, content:"Page 1"}, 
      {id:2, content:"Page 2"}
    ]
  },
  getters: {
    indexPage: state => page => state.pages.find(p => p.id === page)
  }
})

const mapGetters = Vuex.mapGetters

new Vue({
  el: '#app',
  store,
  mounted () {
    console.log(this.indexPage(1))
  },
  computed: {
    ...mapGetters([
      'indexPage'
    ])
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app"></div>

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

After successfully uploading a file, refresh the file list using AngularJS, DropzoneJS, and JSON

In my "file manager page," I am using DropzoneJS for uploading files and AngularJS ng-repeat to display all the saved files. The file list is retrieved through an ng-controller that uses an http.get request to fetch a JSON file with the file list. When Dr ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

How can Vue.js pass an array from a child component to its parent component?

I'm currently developing a contact book app and I have created a modal within a child component that contains a form with several input fields. My goal is to utilize the values entered in the form and add them to the parent component. I have successfu ...

Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string: const filteredString = `${this.filter}`.toLowerCase(); this.filteredCampaigns = this. ...

The $refs property in Vue.js appears empty because of the v-if directive

I have a Vue component that showcases an address but transforms into a form to edit the address upon user interaction. The address input utilizes Google Maps API for autocompletion. Since the input field is hidden or non-existent half of the time, I need t ...

Displaying 'Undefined' instead of 'Cleared messages count' in the Clear Command

My goal is to display the number of deleted messages on an embed, but when the embed is sent, it shows bot deleted undefined messages. Here's a screenshot: I want it to show bot deleted ex: 15 messages. It works fine as a regular message but not on a ...

Having difficulty submitting a form with ajax, while accomplishing the same task effortlessly without ajax

I have been experimenting with submitting a form using ajax to the same .php file. When I submit the form without ajax directly (form action), the database gets updated. However, when I try the same process with ajax, there is no change in the database. H ...

Transform PHP array into a properly structured array or object that can be easily used in JavaScript

My PHP code contains an array that looks like this: $variation = [ attribute_label => "Choose your Color", attribute_name => "pa_choose-your-color", variations => [ "819" => "Red", "820" => "Blue", ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Customize the formatting of linked locale messages in Vue's internationalization (i18n) feature using parameters

Is there a way to link locale messages in vue-i18n with a parameter? { "next": "Next step {step+1}: @:steps[{step}]", "steps": [ "Welcome", // 0 "Briefing", // 1 "Finish" // 2 ...

JavaScript: Receiving an error that function is undefined when working with data binding

Why is my code showing that it's not defined while I'm attempting a simple code with data binding? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="ht ...

When the class name is identical, the click event appears to be malfunctioning

Why isn't the click event working in this code? What am I doing wrong? $(document).ready(function() { $('.dashboardList').click(function() { alert("hello"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1. ...

Can you explain the distinction between $scope.$root and $rootScope?

When looking at controllers, I noticed that $scope includes $root. Can you explain what $root is and how it differs from the $rootScope that can be injected into the controller? ...

Is there a way to display all of them inline in Woocommerce?

Can anyone assist with making each of these inline? <div class="atc_nsv"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <ul> <li><img class="ad lazyloaded" data-src="//cdn.shopify.com/s/files/1/0608/5882/6972/fi ...

Is there a specific method or function that can effectively translate special characters such as into their corresponding representations?

When a user provides input for my script using shell arguments, it would look something like this: Kek kek\nkek\tkek\x43 After receiving the input, Javascript interprets my parameter in a specific way: var parameter="Kek kek\&bs ...

For each item they possess, attach a "!" at the end

Given an array, I am trying to use map to add an exclamation mark to each item in the array. For example: Before - items: ["ball", "book", "pen"] After - items: ["ball!","book!","pen!"] const array = [ { username: "john", team: "red", score: 5 ...

Searching with Vue JS and Firebase using multiple .Where() functions can be achieved by chaining these methods together. This

Looking to search multiple collections, not just brand. I am querying directly from Cloud Firestore Successfully pulled data for brand Trying to incorporate category and description as well, but facing issues Using where() to query Firebase getExchanges ...

Error: Unable to access the `insertUsername` property as it is not defined

When I attempt to submit the login form created by the new.ejs file, instead of being redirected to the expected page, I am encountering an error message that reads: Cannot read property 'insertUsername' of undefined This same error message is ...

Manipulating the DOM with Javascript and jQuery: Adding a new element and retrieving its reference

I am encountering an issue with a Web App that relies on JavaScript and jQuery. Essentially, the website includes a button that triggers a JavaScript function when clicked. Within this function, there are two other functions named Foo and Bar. Foo generate ...

How can you automatically show the current time upon entering a page using React Native?

Is there a way to automatically display the current time when a user enters the page? I currently have code that only shows the current time when the TouchableOpacity is pressed, but I want it to update automatically as soon as the user arrives on the Ne ...