"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

How can I set an object as a variable in JavaScript (specifically React) based on two different conditions?

const router = useRouter(); const { locale } = router; const featureId = props.id; let featureContent; featureContent = locale === "en" ? featureContentEn : locale === "de" ? featureContentDe : lo ...

Having trouble with jQuery UI draggable when using jQueryUI version 1.12.1?

Currently, I am diving into the world of jQuery UI. However, I am facing an issue with dragging the boxes that I have created using a combination of HTML and CSS. My setup includes HTML5 and CSS3 alongside jQuery version 1.12.1. Any suggestions or help wou ...

NPM - Include in package.json without installation

Can a command be executed to validate that the package is a legitimate npm package, include it as a dependency in package.json, but refrain from actually installing it? This question arises from the need to utilize a specific package globally and incorpor ...

Using jQuery Ajax and PHP for Secure User Authentication

Hello everyone, I could really use some assistance right now. The issue I'm facing is that the error div is not showing the content I expect in the success function of my AJAX request. I've tried alerting the response, which returns true if the ...

The function '$.fn.<new_function>' is not a valid function in jQuery

UPDATE: code link with enhanced formatting: UPDATE: code upgraded with enhancements from JSHint http://pastebin.com/hkDQfZy1 I am attempting to utilize $.fn to establish a new function on jQuery objects by this method: $.fn.animateAuto = function(x,y) { ...

Is the syntax incorrect or is there another reason for the empty array being passed, as the "resolve" callback is running before the completion of the for loop?

The for loop will iterate over the length of req.body, executing a Customer.find operation in each iteration. The resolve function will then be called with an array containing the results of all the find operations. let promise = new Promise(function(res ...

JQuery may be successfully loaded, but it is not functioning as intended

Just started dabbling in JQuery (I'm a newbie) but I'm having trouble getting it to work! Initially, it worked a couple of times but then suddenly stopped working (pretty strange). I made some changes and now it doesn't work at all. JQuery a ...

Is Vue the next contender against React Native and Flutter?

I find vue and nuxt very enjoyable to work with. However, I believe that the future lies in mobile development or rather "developing for both mobile and web using the same code." Is there an efficient method to achieve this with vue? Or should I consider ...

Extracting information from a checkbox list displayed within an HTML table

I have a table with multiple rows and two columns in each row. The first column contains text, and the second column consists of checkboxes. While I was able to retrieve the values from the first column, I am struggling to fetch the values of the selected ...

What could be causing my jQuery code to not function properly?

I wrote a small piece of code in jQuery, but I am having trouble executing it. Can someone help me figure out what I'm doing wrong? <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"> & ...

Vue JS encountering Slack API CORS issue while using axios

I am currently developing an application using Capacitor JS & Nuxt JS to interact with the Slack API for setting my Slack status. I have successfully created a Slack App and obtained a xoxp- token, which works perfectly when sending a POST request via Post ...

Vue plugins that emit events

In the scenario where I have a basic Vue plugin that does not contain any components, but simply provides some methods to the user: export default { install(Vue, options) { // Unrelated tasks go here. } Vue.prototype.$foo = () => { ...

Encountering a CORS issue specifically on the client side of a Next.js application when interacting with an API gateway

I've been struggling with this issue for a week now and can't seem to fully describe it. I have a FastAPI server running as a Lambda connected to API Gateway. https://i.stack.imgur.com/S5Zx9.png Both FastAPI and API Gateway have CORS enabled, b ...

Using 'require' within a nested directive that relies on the parent directive in AngularJS

Implementing a sub directive to be utilized in multiple directives is my current challenge. These parent directives share a common controller that has useful methods for updating scope variables within these directives: (potentially changing controllers ...

Using the spread operator on Vuex mutations is not compatible

I am encountering an issue where I cannot use spread operators in a Vuex mutation on Nuxt. Here is the mutation code: EDIT_BALLOON(state, data) { const index = state.list.findIndex(item => item._id === data._id); //state.list[index] = {...data} // ...

Experiencing trouble with setting values in JavaScript?

I have my code set up to display numbers 170 and 122 using Javascript, but I'm not seeing the expected output. <!DOCTYPE html> <html> <body> <button onclick="UidToPost()">Get It</button> <script> ...

The optimal method for computing the Fibonacci sequence using JavaScript

Improving my skills in optimizing algorithms and understanding big-o notation is a priority for me. I devised the following function to compute the n-th Fibonacci number. It works well for higher inputs, but I wonder how I can enhance it. What are the dow ...

Modifying an Object within a for-in loop

Hi there, I'm facing a challenge with updating an object that has child properties in my Angular application. Here is the initial object: $scope.osbStep = { test0Nav : { current : false, comp ...

Leveraging the combination of Express JS and Vue.js within the Electron framework

Can you combine Vue.js and Express JS in a project with Electron JS? How would this work? I currently have a project running on Vue.js and Electron JS, but I'm unsure how to integrate Express JS into it. Any guidance would be greatly appreciated. ...

The Cross-Origin Request has been blocked due to the Same Origin Policy prohibiting access to the remote resource. The reason for this is that the CORS preflight response was unsuccessful

SERVERSIDE // Establishing Headers app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE"); res.header("Access-Control-Allow-Headers ...