I am trying to make a currency converter using react.
I make the request to the API and I got what I need. But when I try to set the state, it gives undefined. I tried some other people's code but it's still not working.
Here's the code
import React from 'react';
const API_URL = {MY API URL};
function App() {
///////////IMPORTANT////////////
const [currency, setCurrency] = useState();
//The function to actually make the fetch or request
function makeApiRequest() {
fetch(API_URL)
.then(res => res.json())
.then(data => {
setCurrency(data); //Sets currency to data
});
}
//Makes a request to the API
useEffect(() => {
makeApiRequest();
console.log(currency); //Outputs 'undefined'
}, [])
///////////IMPORTANT////////////
return (
<h1>Currency Converter</h1>
);
}
and there are no errors, and here is what data returns
{rates: {…}, base: "EUR", date: "2020-04-09"}
base: "EUR"
date: "2020-04-09"
rates:
AUD: 1.7444
BGN: 1.9558
BRL: 5.5956
CAD: 1.5265
CHF: 1.0558
CNY: 7.6709
CZK: 26.909
DKK: 7.4657
GBP: 0.87565
HKD: 8.4259
HRK: 7.6175
HUF: 354.76
IDR: 17243.21
ILS: 3.8919
INR: 82.9275
ISK: 155.9
JPY: 118.33
KRW: 1322.49
MXN: 26.0321
MYR: 4.7136
NOK: 11.2143
NZD: 1.8128
PHP: 54.939
PLN: 4.5586
RON: 4.833
RUB: 80.69
SEK: 10.9455
SGD: 1.5479
THB: 35.665
TRY: 7.3233
USD: 1.0867
ZAR: 19.6383