Issue
I am using a fetch request to get some FX rates from an API. However, I only need to store the rate for a currency that's been previously selected by the user and saved as state (state.currency
).
The example below works well for predefined values (e.g. json.rates.GBP) but I can't find a way to link it with this.state.currency
.
Here is my current code:
var fxRates;
class FxRateCheck extends Component {
constructor() {
super();
this.state = {
currency: "",
isLoading: true
};
}
handleSubmit = () => {
fetch("https://api.exchangeratesapi.io/latest?base=USD")
.then((response) => response.json())
.then((json) => {
fxRates = json.rates.GBP;
// I need to replace GBP with the value of this.state.currency
})
.catch((error) => console.error(error))
.finally(() => {
this.setState({
isLoading: false
});
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Solution
The user sets the currency base in their state, you then need to use the same value as the key when you access a property in a different object.
fxRates = json.rates[this.state.currency];
There are a few other things you need to change though. the global variable fxRates
is generally a bad practice, if you need to use the result in other places in your component consider putting it on the component state.
You should also let the user choose what to compare with. ?base=USD
is hardcoded currently. Maybe consider letting them change that in a future change :)
Heres an example of what I was describing :)
Answered By - John Ruddell
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.