Adding numerous objects to a Vuex store using mutations

I am currently working with the following store setup:

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({

  plugins: [createPersistedState()],

  state: {
    data: [
      {symbol: '', price: ''}
    ]
  },

  mutations: {
    RECEIVE_PRICE(state, {symbol, price}) {
      state.data = {
        symbol: symbol,
        price: price
      }
      // state.data.push({
      //   symbol: symbol,
      //   price: price
      // });
    }
  },

  actions: {
    async FETCH_PRICE({commit}, payload) {
      const url = `https://min-api.cryptocompare.com/data/price?fsym=${payload.symbol}&tsyms=${payload.currency}`;
      const {data} = await axios.get(url);
      commit('RECEIVE_PRICE', {
        symbol: payload.symbol,
        price: data[payload.currency]
      });
    }
  },

  getters: {
    crypto_prices: state => {
      return state;
    }
  }
})

Within my component, I have created a form consisting of three inputs for Symbol, Amount, and Currency.

Upon calling my getter within the component using

computed: mapGetters(['crypto_prices'])
, the data is successfully retrieved from the getter (which is functioning correctly).

However, there is an issue:

Whenever I add a new cryptocurrency, the existing data in my store gets replaced by the new entry. How can I modify my mutation to append the new data instead?

I attempted this by using store.data.push({...}), but it resulted in duplicates...

Answer №1

To achieve this, utilizing the push method is necessary. If duplicates are to be avoided, you must locate an existing entry and replace it with the new one in the following manner:

const index = state.data.findIndex(d => d.symbol === symbol)
if (index === -1) 
  state.data.push({symbol, price});
else 
  state.data[index] = {symbol, price}

Answer №2

When integrating this feature into your store, you will need to invoke an action:

async ADD_CRYPTO({commit}, payload) {
  //Save the data to the database or perform necessary actions. If successful...
  commit('set_crypto', <payload or server data>);
}

After that, you can make use of a mutation to implement it:

set_crypto(state, crypto) {
    state.data.unshift(crypto);
},

It might be beneficial to consider changing the name "data" in your store to something more descriptive like crypto or currencies, as Vue has a specific way of handling the term data.

Additionally, as your store expands, you can simplify things by accessing individual items through getters:

 currencies: state => {
    return state.currencies;
},

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

Tips for refreshing a table component after receiving a notification from a WebSocket in React JS

Currently, I am utilizing React table to load a page that shows a table with data fetched from an API. Additionally, I am listening on a web socket and whenever there is new data sent over the web socket, a console message is printed. My goal now is to a ...

Circular graphs displaying percentages at their center, illustrating the distribution of checked checkboxes across various categories

Looking for a JavaScript script that displays results in the form of circles with percentage values at their centers, based on the number of checkboxes checked in different categories. The circle radius should be determined by the percentage values - for e ...

Trouble accessing data with VueJS 3 axios

Hey there! I'm new to VueJS 3 and currently diving into the Composition API. I recently created a weather website, but I'm encountering difficulties in retrieving data. Below is the function I've been working on: setup() { let weather = ...

"What is the purpose of using the `position: absolute` property for movement transitions while deleting an item from a list

Click here to see an example where items smoothly move in a list when one item is removed. To achieve this effect, the element needs to be styled with: .list-complete-leave-active { position: absolute; } I'm curious as to why it doesn't work w ...

unable to access POST information

I have encountered an issue with getting a basic AJAX POST to function properly. After facing difficulties with using a jQuery .click, I switched to an onclick method. I am unsure if I am making a glaring mistake or if there could be an issue with Apache s ...

Prevent certain dates from being selected in a designated input field

I am facing an issue with disabling certain array dates for a specific input field in a datepicker calendar. Even though I have included the script to exclude those dates, they are not getting disabled for that particular input field. html <input cla ...

"Explore the versatility of React Day Picker with customizable months and weekdays_long

I have implemented the following packages: "react": "^18.2.0", "react-day-picker": "^8.1.0", and I am attempting to translate the months and days into French. However, despite passing the translated arrays to my < ...

Utilizing Jquery Validation to Remove a Class Upon Form Validation Success

In my current registration process, I have a multipart form where each subsequent form is displayed when the next button is pressed without fading effects. Initially, the button appears faded. Here's a simplified version of how I handle the first form ...

Is there a way to choose the final JSON element using Javascript or Google Apps Script?

Imagine if I extracted this data from a constantly updating JSON file. [{ "data": { "member": "Feufoe, Robert", "project": "Random Event", }, "folder": null, "id": 1062110, "spam": null }, { "data": { "membe ...

Developing a universally accessible variable for utilization in various functions

I'm having trouble understanding why 'currentPos.LatLng' is undefined when trying to access it outside the function even though it's part of an object. I want to be able to retrieve the current position values to use them in another fun ...

AJAX request failed to elicit a response

Recently, I've been facing an issue with my AJAX call to the API. Previously, it was functioning correctly and returning a response JSON. However, now I am unable to retrieve any JSON object. When using Mozilla, no error is shown but the response JSON ...

Incorporate the teachings of removing the nullable object key when its value is anything but 'true'

When working with Angular, I have encountered a scenario where my interface includes a nullable boolean property. However, as a developer and maintainer of the system, I know that this property only serves a purpose when it is set to 'true'. Henc ...

Customize the format of the date in X-editable

I have implemented a X-editable date field using JS and HTML. However, when I select a date from the calendar popup, the value displayed in the input box is not following the format "mm/dd/yyyy" as specified. Instead, it shows "Wed Apr 13 2016 20:00:00 G ...

Error: The function $.ajax(...).done(...).fail(...).complete does not exist

Out of nowhere, I started encountering the error message below: TypeError: $.ajax(...).done(...).fail(...).complete is not a function Below is my code snippet: this.sendRequest = function (type, extension, data, successCallback, successMsg, failMsg, ...

Modify the h:outputText value dynamically with the power of jQuery!

Is it possible to use jQuery to dynamically change the value of my OutputText component? This is the code snippet for my component: <h:outputText id="txt_pay_days" value="0" binding="#{Attendance_Calculation.txt_pay_days}"/> I would apprecia ...

Is there a way to bring together scrolling effects and mouse movement for a dynamic user

If you want to see a scrolling effect, check out this link here. For another animation on mouse move, click on this link(here). Combining both the scrolling effect and the image movement might seem challenging due to different styles used in each templat ...

Why isn't my ng-click function functioning properly on Google Maps in AngularJS?

i have two stores in my database and am attempting to display them on a Google map with markers. I have an ng-click function inside the info window to pass the store id, but it seems like ng-click is not working. Is there any alternative method to pass t ...

Harnessing the power of two-way data binding in VueJS

I am looking to utilize Vue's two-way data binding to dynamically update the values of amount and total. The price of a given product is fixed. When users modify the amount, the total = amount * total will be automatically calculated. Similarly, users ...

Conditional compilation in Laravel Mix allows for specific code blocks to be

I'm currently working on a Laravel project and I need to introduce some conditional statements. Within the root folder of the project, there's a file called module_statuses.json which contains JSON variables like this: { "Module1": true, ...

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...