DEV Community

Akash Yadav
Akash Yadav

Posted on

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

Top comments (0)