Vue .filter doesn't work with reactive data sources

I'm currently working on a project that involves creating a dynamic shipping estimate in a Shopping Cart. The challenge I face is retrieving shipping methods from an API endpoint and making the data reactive to update in real-time based on the selected method.

const shipping_estimate = computed(() => {
    // encountering an error here
    return localState.shippingMethods.filter(function (el) {
         return el.price === shippingMethods[selectedShippingMethod];
    });
});

const localState = reactive({
    removingCartItem: false,
    paymentProcessing: false,
    stripe: {},
    cardElement: {},
    customer: {},
    orderError: null,
    loading: false,
    selectedShippingMethod: null,
    shippingMethods: {}
}); 

onMounted(async () => {
    localState.loading = true;

    await axios
       .get("/api/shipping-method")
        .then((response) => {
            localState.shippingMethods = response.data.data
            localState.loading = false;
    })
});

An issue arises with the following error:

TypeError: localState.shippingMethods.filter is not a function

When checking in Vue dev tools, localState.shippingMethods shows as an array instead. How can I effectively filter data stored within a reactive object?

Answer №1

It is important to initialize the shippingMethods property as an empty array:

const localState = reactive({
   ...
    shippingMethods:[]
}); 

This is necessary because the computed property will evaluate this property during the initial rendering, and it should be empty at that point.

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

JavaScript resets the timer whenever the page is refreshed

Is there a way to maintain the timer in a quiz even after refreshing the page? <html><h1>Js Timer</h1> <div style="font-weight: bold;" id="quiz-time-left"></div> <script type="text/javascript"> var total_seconds = ...

The table row disappears but the value persists

I have designed a table where users can perform calculations. However, when a row is deleted, the values from that row appear in the row below it and subsequent rows as well. What I want is for the user to be able to completely remove a row with its values ...

How can I securely save a user's login information using ExtJS without saving it multiple times?

Currently, I am utilizing Ext.Ajax.request() to access a PHP page that provides user-specific information during the login process. In order to store variables such as cookies and session information in ExtJS, I have created a model with necessary fields a ...

How can JQuery be utilized to extract the information stored in the "value" parameter of a chosen option?

I have a dropdown menu that dynamically populates its options with numbers. Here is the code for that: <select name="TheServices" id="services-selector"> <option value="" disabled selected hidden>Static Select ...

Accessing location information using jQuery from Google's Geocoding API

Recently, I've been delving into the realm of Google Maps Geocoding and attempting to comprehend how to decipher the JSON data that it transmits back. This snippet showcases what Google's response looks like: { "results" : [ { ...

Define JSON as writeable: 'Error not caught'

I'm facing an issue with a read/write error in my JavaScript code because the JSON file seems to be set as read-only ('Uncaught TypeError: Cannot assign to read only property'). How can I change it to writable? Should I make changes in the J ...

Using Javascript to pass the value of a selected checkbox

I am having an issue with passing a row value to a different function when a user clicks on a checkbox in the last column of a table. The code I have written doesn't seem to be firing as expected. Can anyone help me figure out what might be missing in ...

Why does xpath insist on choosing spaces instead of actual elements?

Here is a list of countries in XML format: <countries> <country> <code>CA</code> <name>Canada</name> </country> ... etc... </countries> I am looking to extract and loop through these nodes, so ...

Guide to incorporating Bootstrap and its dependencies into a Chrome extension powered by Vue using npm

As I delve into the world of webpack, vue, and vuex to create a chrome extension, I encountered an issue with loading Bootstrap 4 within the extension. Despite using the correct path for the node modules folder, I keep getting a file not found error when t ...

Tips for executing gulp tasks in the command line

As a newcomer to Gulp, I've encountered an issue with executing a task named task1 in my gulp.js file. When I enter "gulp task1" in the command line, it opens the gulp.js file in Brackets editor instead of running the task as expected. Can anyone offe ...

The UglifyJsPlugin in Webpack encounters an issue when processing Node modules that contain the "let" keyword

Below is the code snippet from my project which utilizes Vue.js' Webpack official template: .babelrc: "presets": [ "babel-preset-es2015", "babel-preset-stage-2", ] webpack.prod.config.js new webpack.optimize.UglifyJsPlugin({ compress: { ...

Tips for Angular4: ensuring ngOnDestroy completion before navigation

My task involves managing a list of objects where the user can choose an object to edit using a child component. However, when the user returns to the list component, the child component needs to clean up in the ngOnDestroy method, which includes making a ...

The process of altering a property in input data within Vue.js

I have a component called Input.vue that displays a label and an input field of some type. Here is how it looks: <template> <div class="form-element"> <label :for="inputId" :class="['form-element-tit ...

Triggering AWS Lambda functions with SQS

Utilizing AWS and SES for sending emails and SMS through a Lambda function using NodeJs. I need to make more than 1k or 500 REST API calls, with the average call taking 3 seconds to execute a single lambda function request. It is essential to process mul ...

initiate scanning for HTTP GET calls

My current project involves using electron to create an application that serves multiple image files through a webserver using express. Another app built for Android is responsible for retrieving and posting files to this server. While I have successfully ...

Error: Failed to find the location because geolocate has not been defined

I searched extensively online for a solution to my problem without success, so I am reaching out to seek your assistance. I am attempting to utilize the Google Address auto-complete API within an asp.net core framework. In my razor file, I have included: ...

Organize the JSON data in a particular manner

I have a set of JSON data that looks like this: [ { "name": "Event 1", "sponsors": [ { "name": "Walmart", "location": "Seattle" }, { "name": "Target", "location": "Portland" }, { ...

Configuring routes for Angular4 router is a vital step in creating a

Issue: I am currently setting up routes for my application, aiming to structure the URL as https://localhost:4200/hero=id, where the 'id' will be dynamically selected. However, this setup is not functioning as expected. If I attempt to use a URL ...

When hovering over various div elements in HTML

I've been experimenting with some code lately, and I'm trying to change the text color of a menu element when hovering over it. I can alter the background color just fine, but for some reason, the text color remains unchanged. Can anyone offer a ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...