I am working on a currency calculator using react.js
I am fetching the latest exchange rates and storing them in state using the getRates function:
getRates(currencyShortcut){
fetch('https://api.fixer.io/latest?base='+currencyShortcut)
.then(response => response.json())
.then(parsedJson => this.setState({currencyRates:parsedJson}))
.catch(error => console.log('fetch error - ', error))
}
These rates are then used to calculate the amount for a given input value, which is displayed on the screen as shown below:
calculateCurrenciesValues(curr,userInput){
let currency1val,currency2val;
const rate = this.state.currencyRates.rates[this.state.currency2.shortcut];
if(curr === 1){
currency1val = userInput;
currency2val = Math.round(rate*userInput*100)/100;
}else{
currency1val = Math.round(userInput/rate*100)/100;
currency2val = userInput;
}
this.setState({
currenciesValues:[currency1val,currency2val]
})
}
The initial HTTP request is made within the componentWillMount method
componentWillMount(){
this.getRates('USD');
}
If a user selects a different currency from the list, the state needs to be updated with new rates. Here is the handler for changing the currency:
changeCurrency(currFlag,currShortcut,currSymbol){
const selectedCurrency = {
path:currFlag,
shortcut:currShortcut,
symbol:currSymbol
};
const {listOfCurrencies,currency1,currency2,currenciesValues,currencyRates} = this.state;
if(this.state.listOfCurrencies.displayFor === 1 ){
this.getRates(currShortcut);
this.setState({
currency1:selectedCurrency
})
this.calculateCurrenciesValues(1,currenciesValues[0])
}
else{
this.setState({
currency2:selectedCurrency
});
this.calculateCurrenciesValues(2,currenciesValues[1])
}
this.setState({
listOfCurrencies:{
display:!listOfCurrencies.display
}
})
}
After changing the currency, the calculation should ideally be done with the freshly acquired data. However, I am facing an issue where the calculation is not updating with the new rates after changing the currency.
Any suggestions on how to ensure that the calculation uses the most up-to-date exchange rates?