0

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.

enter image description here

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.

enter image description here

This only happens when I refresh the page. If I edit my code and save, webpack recompiles and I receive data as intended.

enter image description here

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;
lucasczr
  • 13
  • 2
  • `data` doesn't immediately update. `setData` is asynchronous. This is expected. – Evert Sep 07 '22 at 21:07
  • setData is async, see https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately – James Sep 07 '22 at 21:08

1 Answers1

0

Well you can't query data right after you've set the data, cause that will change it and re-renders the component, only then the data is set. Also you get the log twice most likely due to the fact that you're using React 18 where there is a change of behavior.

I suggest for you to read: https://www.techiediaries.com/react-18-useeffect/