DEV Community

Akash Yadav
Akash Yadav

Posted on

1

Currency Conversion Utility: React Hook vs. Functions

*Heading: Simplifying Currency Conversion with React Hooks and Functions
*

Description:
This code snippet provides a convenient way to perform currency conversion operations in a React application. It offers two main functionalities: retrieving exchange rates for different currencies and converting amounts from one currency to another. The code presents two implementation approaches: one using standalone functions and the other leveraging React custom hooks.

Standalone Functions: The getExchangeRate and exchangeAmount functions handle currency exchange logic independently. They are straightforward and can be easily utilized anywhere in the application.

React Custom Hook: The useCurrencyConverter hook encapsulates currency-related state management and data fetching logic. It provides a clean and reusable solution for components requiring currency information. The hook fetches currency data based on the provided currency code and date, storing the information in state for easy access.

Both approaches offer flexibility and efficiency, allowing developers to choose the method that best suits their project's requirements and coding style.

import axios from "axios";
const { useEffect, useState } = require("react")

const getExchangeRate = async (from) => {
    try {
        const response = await axios.get(`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${from}.json`);
        const data = response.data;
        return data[from];
    } catch (error) {
        throw error;
    }
}

const exchangeAmount = async ({ from, to, amount }) => {
    try {
        const exchangeRate = await getExchangeRate(from);
        const rate = exchangeRate[to.toLowerCase()];
        return (amount * rate).toFixed(2);
    } catch (error) {
        throw error;
    }
}


function useCurrencyConverter() {
    const [currencies, setCurrencies] = useState({});

    const currencyInfo = async ({ from, podate }) => {
        try {
            const response = await axios.get(`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/${podate}/currencies/${from.toLowerCase()}.json`);
            setCurrencies(response.data[from.toLowerCase()]);
        } catch (error) {
            throw error;
        }
    }

    return { currencies, currencyInfo };
}


export default useCurrencyConverter;
export { exchangeAmount }


Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay