Refactor sidebar navigation
This commit is contained in:
74
src/contexts/CurrencyContext.tsx
Normal file
74
src/contexts/CurrencyContext.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
|
||||
export type Currency = 'USD' | 'EUR' | 'GBP' | 'MXN' | 'COP' | 'ARS';
|
||||
|
||||
interface CurrencyContextType {
|
||||
currency: Currency;
|
||||
setCurrency: (currency: Currency) => void;
|
||||
formatAmount: (amount: number) => string;
|
||||
symbol: string;
|
||||
exchangeRates: Record<Currency, number>;
|
||||
}
|
||||
|
||||
const exchangeRates: Record<Currency, number> = {
|
||||
USD: 1,
|
||||
EUR: 0.92,
|
||||
GBP: 0.79,
|
||||
MXN: 17.5,
|
||||
COP: 3950,
|
||||
ARS: 350
|
||||
};
|
||||
|
||||
const currencySymbols: Record<Currency, string> = {
|
||||
USD: '$',
|
||||
EUR: '€',
|
||||
GBP: '£',
|
||||
MXN: '$',
|
||||
COP: '$',
|
||||
ARS: '$'
|
||||
};
|
||||
|
||||
const CurrencyContext = createContext<CurrencyContextType | undefined>(undefined);
|
||||
|
||||
export const CurrencyProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [currency, setCurrency] = useState<Currency>(() => {
|
||||
const saved = localStorage.getItem('preferred_currency');
|
||||
return (saved as Currency) || 'USD';
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem('preferred_currency', currency);
|
||||
}, [currency]);
|
||||
|
||||
const formatAmount = (amount: number): string => {
|
||||
const convertedAmount = amount * exchangeRates[currency];
|
||||
const symbol = currencySymbols[currency];
|
||||
|
||||
return `${symbol}${convertedAmount.toLocaleString(undefined, {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2
|
||||
})}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<CurrencyContext.Provider
|
||||
value={{
|
||||
currency,
|
||||
setCurrency,
|
||||
formatAmount,
|
||||
symbol: currencySymbols[currency],
|
||||
exchangeRates
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</CurrencyContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useCurrency = () => {
|
||||
const context = useContext(CurrencyContext);
|
||||
if (!context) {
|
||||
throw new Error('useCurrency must be used within a CurrencyProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user