Iām trying to get data from the Binance API using an async function which awaits the response and then parses It to JSON.
If I console log this response data, I get the expected array of data. However, for some reason, it console logs twice.
The problem I have is whenever I try to use state to set this response data into a variable. After I set the data, it console logs undefined.
This only happens when I refresh the page. If I edit my code and save, webpack recompiles and I receive data as intended.
Here is my code
import React, { useEffect, useState } from "react";
const endpointUrl = "https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=5";
const Test = () => {
const [data, setData] = useState();
useEffect(() => {
const fetchApi = async () => {
const response = await fetch(endpointUrl);
const responseData = await response.json();
// This works and logs the desired data
console.log(responseData);
// This dosent work and logs undefined
setData(responseData);
console.log(data);
};
fetchApi().catch(console.error);
}, []);
return (
<div>
<ul>Test</ul>
</div>
);
};
export default Test;