The function vue.findIndex is not recognized as a valid function

Encountered an issue with the findIndex() function

Uncaught (in promise) TypeError: state.carts.findIndex is not a function

The cartId includes rowId, qty, sizeVal, and image

Methods

    updateCart() {
        this.$store.dispatch('updateCart', this.cartId)
    }

State

state: {
    carts: [],
},

Vue Inspect Carts

031e0275ef3746070e80d81199bd2580:Object {
    id:1
    name:"T-Shirt"
    options:Object {
        image:"products\July2018\4TXSMgf6eAdrOlaxAMiX.jpg"
    }
    size:"l"
    price:551
    qty:2
    rowId:"031e0275ef3746070e80d81199bd2580"
    subtotal:1102
    tax:115.71
}

mutations

    updateCart(state, rowId) {
        const index = state.carts.findIndex(cart => {cart.rowId == rowId});
        // console.log(index)
            state.carts.splice(index, 1, {
                'qty': cart.qty,
                'size': cart.sizeVal,
            })
    },

Action is functioning correctly

Actions

    updateCart(context, cart) {
        return new Promise((resolve, reject) => {
            axios.patch(`update/cart/${cart.id}` , {
                id: cart.rowId,
                qty: cart.qty,
                size: cart.sizeVal,
                image: cart.image
            })
            .then(response => {
                context.commit('updateCart', response.data)
                resolve(response)
            })
            .catch(error => {
                reject(error)
            })
        })

    },

Looking to resolve the error encountered while updating state.carts

Your assistance on resolving this issue will be greatly appreciated

Thank you

Answer №1

It seems that your state.carts is actually an object and not an Array. The method findIndex is specifically designed for arrays, as explained in the documentation.

When used on an array, the findIndex() function will return the index of the first element that matches the condition provided in the testing function. If no match is found, it will return -1.

Answer №2

Implement a PolyFill function as a globally imported mixin in Vue.

 const getIndex = (list, targetValue) => {
    let resultIndex;
    const found = list.some((item, index) => {
      resultIndex = index;
      return item === targetValue;
    });
    return found ? resultIndex : -1;
  };

Answer №3

Utilizing findIndex as an ES6 array functionality necessitates browser support, alternatively consider implementing polyfill or transpile tools such as babel.js.

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

Ways to automatically check a checkbox using jQuery

Is there a way to use jQuery to programmatically click a checkbox? I am trying to create a hidden checkbox that will be checked when a user clicks on a specific element, but my current code is not functioning as expected and I am unsure why. You can view ...

JavaScript - Issues with Cookie Setting

I created a function for setting cookies: function storeCookie(cname, cvalue, exdays){ var d = new Date(); d.setTime(d.getTime() + (1000*60*60*24*exdays)); var expires = "expires="+d.toGMTString(); document.cookie = cname + "=" + cvalue + ...

Unable to retrieve accurate Boolean data through ajax request

Imagine a scenario where we are working with the following Ajax request: $.ajax({ url:'myURL.php', data:{ ac:'do', isDoable:false } }); Now, on the backend, when processing the call data, the isDoable param ...

Tips for formatting numerical output in EJS by rounding the value

I am displaying a value in EJS and I am looking to format it to show fewer decimal places. This is related to the EJS engine on the frontend. Value displayed: 4.333333333333333 I want it to be displayed like this: 4.3 The EJS code snippet used: <p cl ...

Guide on transforming the popup hover state into the active state in vue.js through a click event

My code currently includes a popup menu that shows up when I hover over the icon. However, I need to adjust it so that the popup changes its state from hover to active. Intended behavior: When I click the icon, the popup should appear and then disappear w ...

What is the best way to handle form data for JSON manipulation in jQuery?

var checkedValues = $('.required:checked').map(function () { return this.value; }).get(); var arr = new Array(10); alert(checkedValues); alert("number of values in it " +checkedValu ...

JavaScript: Share module contents internally through exporting

When working with Java, there are 4 different visibility levels to consider. In addition to the commonly known public and private levels, there is also the protected level and what is referred to as the "default" or "package-local" level. Modifier Clas ...

Having trouble updating a form in React.js that relies on state for its data

My goal is to perform a basic action: add data, pass it back to the main component, and display a list of items that can be accessed and edited in a form. Here is the key part of the code: class SimpleForm extends React.Component { constructor() ...

Error: Sorry, there was an issue with the code (React)

I'm attempting to build a React project without Node, and I'm trying to call a JS file from an HTML file. This is just a simple example for learning purposes. However, I keep encountering the Uncaught SyntaxError: Unexpected token '<&apos ...

What is the process for sending a parameter in getStaticProps within Next.js

Is there a way in NextJS to call an API when a user clicks the search button and display the relevant result? Thanks for your input! The API I'm currently utilizing is , with "Steak" referring to the specific food item of interest. In my development ...

changing the css transformation into zoom and positioning

My goal is to incorporate pinch zoom and panning using hardware-accelerated CSS properties like transform: translate3d() scale3d(). After completing the gesture, I reset the transform and switch to CSS zoom along with absolute positioning. This method ensu ...

Encountered an issue while trying to register a service worker: "[ERROR] Cannot import statement outside

With the utilization of register-service-worker, the boilerplate for registerServiceWorker remained untouched. /* eslint-disable no-console */ import { register } from 'register-service-worker'; if (process.env.NODE_ENV === 'production&ap ...

Blank area located at the bottom of the document

I'm having trouble designing a webpage without a scroll bar because there isn't much content to display on the page. I've tried searching for solutions and following steps to fix the issue, but I haven't had any success. If anyone can a ...

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

Randomize checkbox selection using Javascript and Bootstrap

I'm in a bit of a bind with my webpage and could really use some help to figure it out. Here's the issue: On my website, there's a table of players. Each player has two checkboxes on their line: one to show if they are active (checked), and ...

Unexpected behavior encountered when using TypeScript type declarations

I am currently working on a Gatsby side project incorporating Typescript for the first time. I initially expected Typescript to behave similarly to PHP type declarations, but I have encountered some unforeseen issues. Despite feeling confident in my Typesc ...

Is there a way to ensure that the vertical scrollbar remains visible within the viewport even when the horizontal content is overflowing?

On my webpage, I have multiple lists with separate headers at the top. The number of lists is dynamic and can overflow horizontally. When scrolling horizontally (X-scrolling), the entire page moves. However, when scrolling vertically within the lists, I wa ...

Searching for data in Ag grid Vue using a filter

Can someone help me create a search filter in ag grid vue like the one shown in this image? Image link: https://ibb.co/cwVq7DD For documentation, refer to: https://www.ag-grid.com/vue-data-grid/tool-panel-columns/#read-only-functions I attempted to impleme ...

Combining synchronous and asynchronous code in JavaScript with Node.js and MongoDB

Check out this code snippet: var re = new RegExp("<a href=\"(news[^?|\"]+).*?>([^<]+)</a>", "g"); var match; while (match = re.exec(body)){ var href = match[1]; var title = match[2]; console.log(href); db.news.fin ...

npm run is having trouble locating the graceful-fs module

I am currently enrolled in a course on DjangoRest and React. While I have experience with npm and Python, I have encountered an error that I am unable to resolve. Everything was going smoothly until I ran "npm run dev." package.json file { "name": "fron ...