Is there a way to verify past data in a Vue component post-rendering?

Currently, I am in the process of developing a straightforward market cap checker for cryptocurrencies similar to coinmarketcap by utilizing the Coingecko API.

I have successfully managed to retrieve and display the data without any issues. Additionally, I update the data every 2 minutes.

However, my next objective is to determine whether the latest price is higher or lower than the previous price.

To achieve this, I utilize a v-for loop and send specific data to my "tokenComponent" for rendering purposes as shown below:

<template>
  <div id="app">
    <div class="container mx-auto">
      <div class="pt-6">
        <h1 class="text-2xl font-bold">Crypto Monkey Cap</h1>
        <div v-for="token in listTokens" :key="token.id">
          <div class="py-6">
            <token-component
              :name="token.name"
              :price="token.current_price"
              :mcap="token.market_cap"
            ></token-component>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TokenComponent from "./components/tokenComponent.vue";

export default {
  name: "App",
  components: {
    TokenComponent,
  },
  data() {
    return {
      listTokens: [],
      lastPrice: 0
    };
  },
  mounted() {
    this.getTokens();

    setInterval(() => {
      this.getTokens()
    }, 30000);
  },
  methods: {
    getTokens() {
    fetch("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd")
      .then((response) => response.json())
      .then((data) => {
        this.listTokens = data;
      });
    }
  }
};
</script>

In addition, here's the tokenComponent code:

<template>
  <div class="py-4 border-2 rounded-lg">
    <div class="flex justify-around">
      <h2>{{ name }}</h2>
      <h2>{{ price }} $</h2>
      <h2>{{ mcap }} $</h2>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    name: { required: true },
    price: { required: true },
    mcap: { required: true }
  }
};
</script>

My goal now is to include a conditional class in the price data based on whether the last price is higher or lower than the new one...

(As a beginner in Vue.js, any assistance would be greatly appreciated!)

Answer №1

To accurately determine if the current price is higher or lower than the previous one, it is advisable to store past prices and compare them. Utilize Arrays for this purpose.

Below is a brief example demonstrating how to use setInterval instead of continuously fetching new prices in order to showcase indicators:

new Vue({
  el: "#app",
  data: () => ({
    prices: [1]
  }),
  methods: {
    stonks(index) {
            if (index > 0) {
        return (this.prices[index] - this.prices[index-1]) > 0
            ? 'green' : 'red'
      }
    }
  },
  
  mounted() {
    setInterval(() => {
      this.prices.push(Math.floor(Math.random() * 10) + 1)
    }, 2000)
  }
})
.prices {
  display: flex;
  flex-direction: row;
  padding: 10px;
}

.price {
  border:1px solid #bbb;
  border-radius: 5px;
  padding: 10px;
  width: 32px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  margin-right: 5px;
  position: relative;
}

.stonks {
  position: absolute;
  background: grey;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  top: 0;
  right: 0;
  margin-top:-8px;
  margin-right:-8px
}

.stonks.red { background: red; }
.stonks.green { background: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div class="prices">
    <div 
      v-for="(price, index) in prices" 
      :key="index" 
      class="price"
     >
      {{ price }}
      <div class="stonks" :class="stonks(index)" />
    </div>
  </div>
</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

What is the best way to extract data from an array of objects in a JSON response?

I am currently exploring the utilization of API's in React. Right now, I am developing a search input feature for country names using the Rest Countries API. The data is being pulled from . However, I am facing a challenge in handling this data as it ...

Default Data Configuration for Mongoose

Exploring the realm of node.js and the MEAN stack, I am venturing into the creation of an application. Within this application, there exists a need for default data in the database. My goal is to ensure that this data is populated automatically upon the ap ...

What is the best way to apply a class to a container when a component in AngularJS receives focus or is clicked?

I am trying to apply a class to the container when either the input field is focused or when the dropdown component receives focus or is clicked. The class should be removed when the focus is lost. The requirement is for the input container to have the &a ...

Material UI Snackbar background color not able to be changed

Currently, I'm working on an ErrorHandler component in React.JS that displays a Material UI Snackbar whenever it catches an error. The issue I'm facing is trying to change the background color of the Snackbar to red, which seems to be problematic ...

A guide on obtaining a vue-apollo instance using the @vue/composition-api and nuxt.js

Is there a way to set up vue-apollo in conjunction with @vue/apollo-composable for integration with @vue/composition-api or Vue3.0? Although I am able to get a default apolloClient by using @nuxtjs/apollo: import { DefaultApolloClient } from "@vue/apollo ...

Invoke a fresh constructor within a $get method in Angular's provider

I'm encountering an issue where I am attempting to utilize a function as a constructor inside the `.provider`, but I'm unable to instantiate a new constructor when it's within the `$get`. Here is my provider setup - this.$get = $get; ...

Implementing event handlers with 'v-on' on dynamically inserted content using 'v-html' in Vue

Can Vue allow for the addition of v-on events on strings included in v-html? In this scenario, clicking the 'Maggie' link doesn't produce any action. It appears that it's not recognized by Vue. Is there an alternative method to achieve ...

Having trouble loading HDRI image as environment using Three.js

I recently started using Three.js and am currently tackling a project that involves utilizing an HDRI file for environmental mapping for lighting and reflection purposes. I've been experimenting with loading HDRI files using the HDRCubeTextureLoader a ...

Prevent scrolling after every time the mouse wheel is used

I have created a function that increments a class on a list item, here is the code snippet: var scrollable = $('ul li').length - 1, count = 0; $('body').bind('mousewheel', function(e) { if (e.originalEvent.wheelDelta / ...

In JavaScript, the clearTimeout function may not always return a

Could someone please help me troubleshoot the issue in my code snippet below? I am trying to declare a public variable and assign it to a setTimeout function. If the variable is not null, I want to clear the timeout before setting it again. However, when ...

React components function similar to objects in object-oriented programming

When creating a React component, I used React.createClass() method. module.exports = React.createClass({ // input-field-units.jsx file is where this code resides displayName: 'input-field-units', render: function () { return ( ...

Initiate an AJAX request within an existing AJAX request

On one of my pages, page A, I have a form that passes parameters to a script using AJAX. The results are loaded into div B on the same page. This setup is functioning properly. Now, I want to add another form in div B that will pass parameters to a differe ...

Locate the nearest span element and update its CSS class

On my page, there is a section with the following code: <h5 class="text-center" id="findStore" style="width:260px"> <a data-toggle="collapse" data-parent="#accordion" href="#@item.ProductId" aria-expanded="true" aria-controls="@item.ProductId ...

What is the best method for validating a div element using Angular UI Bootstrap?

When I try to display an array of objects in a view, my issue arises when I place a div element inside the li and ul tags. The challenge now is to validate elements such as "number", "url", and "email" on blur and keyup events. Some elements may be require ...

having trouble retrieving the DOM element in Vue.js

I'm currently working on developing a drag and drop component, but I've encountered an issue with selecting the div using getElementById. When I try to do so, I receive an error message stating: Uncaught TypeError: Cannot read property 'addE ...

Using Node.js to handle reading files and dealing with undefined or null values

The get method is responsible for receiving a userid with an initial total number of points defined in the stcok.json file, along with various transactions stored in another file. Below are some sample entries from the stock JSON: [ { "user" ...

Incorporate a unique CSS class into the `.ck-content` element within CKEditor5 and Vue2

Is there a way to add a custom CSS class to the element .ck-content, also known as the editable formatted text container, in CKEditor5 and Vue2? https://i.sstatic.net/KG7Et.png The ck-content represents the input field, which needs to be distinguished fr ...

Pull in class definitions from the index.js file within the node_modules directory

In my project, I have the package called "diagram-js" in the node_modules. The file node_modules/diagram-js/lib/model/index.js contains multiple class definitions as shown below: /** * @namespace djs.model */ /** * @memberOf djs.model */ /** * The b ...

A nested DragSource component within a parent DragSource component in React DnD

In my project, I am working with a tree structure that consists of a root "Tree" component containing a list of root "TreeNodes". Each TreeNode can have an arbitrary number of children. Within the render method of the TreeNode component, I iterate over th ...

Inserting items into a JSON array

Is there a way to add a new ID to my data array without creating a new object for each addition? Existing Data: [{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"}, {"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92 ...