Building a Currency Converter in Vue3

Currently, I am in the process of incorporating a convert() function into my Vue3 project.

Within my functions.js file, I have stored some essential "global" functions.

import axios from 'axios'

let functions = {}

functions.convert = async (amount, currencySetting) => {
  const result = await getRate(currencySetting)
  const rateData = result.data
  const rate = rateData[`EUR_${currencySetting}`]
  const converted = rate * amount
  return Math.round(converted)
}

function getRate(currency) {
  const apiKey = process.env.VUE_APP_CURRENCY_API_KEY
  return axios.get(
    `https://free.currconv.com/api/v7/convert?q=EUR_${currency}&compact=ultra&apiKey=${apiKey}`
  )
}

export default functions

When trying to utilize this function within a component, I am implementing it as follows:

<script>
import functions from '@/functions.js'

export default {
  name: 'SltResult',
  props: {
    data: {
      type: Object,
      required: true
    }
  },
  computed: {
    formattedIrp() {
      if (this.data.irp != 'n/a') {
        const currencySetting = this.$store.state.currency.currency
        if (currencySetting != 'EUR') {
            const convertedIrp = functions.convert(this.data.irp, currencySetting)
            return convertedIrp + currencySetting
        } else {
            return this.data.irp + '€'
        }
      }
      return this.data.irp
    }
  }
}
</script>

Unfortunately, I am encountering issues as the function is returning a pending Promise result. Can anyone provide insight into where I may be going wrong? As a beginner in Vue and JS, any guidance would be greatly appreciated...

Answer №1

Your code has a couple of issues that need to be addressed.

  1. Structural problem. Having an ajax call within a computed property is not recommended. It would be better to use a regular method instead.
  2. Formatting problem. The function convert is asynchronous, so you will need to await its result before proceeding.

Below is a revised version of your code:

<script>
import utilities from '@/utilities.js'

export default {
  name: 'UpdatedResult',
  data: () => ({
    formattedIrp: null,
  }),
  props: {
    data: {
      type: Object,
      required: true
    }
  },
  mounted() {
      if (this.data.irp != 'n/a') {
        const currencySetting = this.$store.state.currency.currency
        if (currencySetting != 'EUR') {
          utilities.convert(this.data.irp, currencySetting).then(result => {
            this.formattedIrp = result + currencySetting;
          })
        } else {
            this.formattedIrp = this.data.irp + '€'
        }
      }
      this.formattedIrp = this.data.irp
    }
  }
}
</script>

Answer №2

Here is a solution for you:

async function fetchExchangeRate(currency) {
  const apiKey = process.env.API_KEY_FOR_CURRENCY_CONVERSION
  return axios.get(
    `https://free.currconv.com/api/v7/convert?q=EUR_${currency}&compact=ultra&apiKey=${apiKey}`
  )
}

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

When using Javascript, the click function is returned as not being a valid function

I am working on a project with two PHP files - index.php and loadimages.php. The index.php page contains a thumbnail gallery and a canvas. The images in the thumbnail gallery are populated by loadimages.php. Here is a snippet of the code from loadimages.ph ...

Unable to save a URL link in MySQL database using JSON and PHP

I am seeking some insightful advice regarding my college assignment. This time around, I have to create yearbooks using Phonegap and it's my first experience working with AJAX, JSON, and JQuery Mobile. Instead of uploading an image directly into the ...

Activate a Transition Animation upon insertion into the DOM

I'm attempting to insert a new element into the DOM and then apply a new class to activate a transition animation. // -- 1 -- Circle is already present in the DOM // <div class="circle circle1 hwaccel"></div> $('.circle1').addCl ...

Angular ng-boostrap modal automatically refreshes upon detecting mouse movement with an embedded video

Currently, I am facing an issue with my Angular 7 ng-bootstrap modal. The problem arises when the modal, which includes a video player within an <iframe>, is moved to the production system. Whenever there is any mouse movement detected, the video get ...

Employ Angular within the parameters of a JavaScript function call

My goal is to incorporate Google Maps into my webpage for various locations (lieux). Within the HTML page, I have the necessary function set up for Google Maps. <script> function initialize(long,lat) { var mapCanvas = document.getElementById( ...

Limited functionality: MVC 5, Ajax, and Jquery script runs once

<script> $(function () { var ajaxSubmit = function () { var $form = $(this); var settings = { data: $(this).serialize(), url: $(this).attr("action"), type: $(this).attr("method") }; ...

Error in Node Redis-OM: the function generateId of this[#schema] is not recognized

Hey everyone, I'm currently facing an issue with saving an entity into a Redis repository. The driver is connected correctly, the schema and repo are set up as expected. However, when I attempt to save the entity, I encounter the following exception: ...

Seamless transitioning between HTML sections

I understand the concept of animating transitions in HTML sections to create a smoother effect. For example, this website: http://en.wikipedia.org/wiki/Dobroslav_Jevdevic Utilizes HTML sections. Clicking on a link from the table of contents takes you di ...

Using jQuery Flot to dynamically load data onto the x-axis from an array

I have a jQuery flot graph that loads the x-axis data as follows: xaxis: { tickColor: 'transparent', tickDecimals: 0, ticks: ticks }, When I manually set the ticks variable like this, everything works fine and the x-axis displays the 7 da ...

When a div is created outside of the viewport, the overflow scroll feature will fail to function properly

I am currently working on developing a full screen slider with a unique feature on the last slide: a horizontal scrolling area. To achieve a smooth animation, I am using CSS translations to bring the div within the viewport. Oddly enough, the scrollbar do ...

Error encountered during the "next build" process: Next Js - Providers/getProviders() returns a Fetch

Currently, I am in the process of developing my application using Next.js and implementing providers with next-auth. Everything runs smoothly when I use "npm run dev", however, I encounter an error when I switch to "npm run build". Here is a screenshot of ...

Problem encountered with JavaScript getter on iOS 5

While implementing JavaScript getters in my iPad-optimized website, everything was working perfectly until I updated to iOS 5. Suddenly, the site stopped functioning properly. After thorough investigation, I discovered the root cause of the issue. I have ...

Is it necessary to trim strings prior to employing the map function?

I am working on extracting all input values from a user-generated page and storing them in an array to make an ajax call for data processing. Here is my approach: $('#save').click(function(){ var data = $('*[data-array]').map(funct ...

I'm facing an issue with my GraphQL resolvers due to a circular dependency

After modifying my repositories to directly return the GQL resolvers, everything was going smoothly until I encountered a circular dependency issue. Now, I have two repositories that rely on each other, creating a dilemma that JavaScript cannot easily reso ...

A guide on immediately invoking a method when a class is initialized in JavaScript

I'm having some trouble with a class I created to handle user information. When I try to add an init() function to the class so that it runs as soon as the class is initialized, I keep getting a SyntaxError. I've tried following the advice from ...

What could be causing my POST request to fail in creating a new JSON file using JavaScript?

I'm troubleshooting why my post request isn't generating a new JSON file. I've implemented a JS POST fetch request in the code snippet below. //All variables are assumed to be defined fetch(lowercaseUsernameStr+'_profile_data.json&ap ...

"Encountering a problem with a function showing an undefined error

Trying to incorporate a slider feature into my application led me to reference this w3schools sample. However, upon loading the page, the images briefly appear before disappearing. Additionally, clicking on the arrow or dots triggers an error stating: U ...

New color scheme in Visual Studio Code for JavaScript and TypeScript files within Visual Studio 2017

I am interested in importing or setting a Visual Studio Code color theme for JavaScript and TypeScript files in Visual Studio 2017. Specifically, I would like to customize the color theme for files with extensions: .js, .jsx, .ts, and .tsx. If individual f ...

I am currently struggling to make the userID route parameter function correctly with react-router-relay

I've been diving into the world of React Relay and GraphQL with react-relay-router, but I'm having trouble getting the params in my routes to function correctly. Specifically, I'm struggling with the "/Maps/:userID" route. Let me share my r ...

Angular-UI/Bootstrap: Experimenting with a controller incorporating a dialog box

Hello there, I have a controller that utilizes a Dialog from the angular-ui/bootstrap framework: function ClientFeatureController($dialog, $scope, ClientFeature, Country, FeatureService) { //Get list of client features for selected client (tha ...