useEffect and useState hooks unique issue. No Data on first load


I’m just hacking at / learning react. Here is the deal. This works, you click the button, it runs the refreshhandler and boom state gets updated and renders new data on the page like magic. But what if you are just loading the page the first time? Well you would want the data to be there already right?

So I useEffect with an empty [] array trailing it so it will only run on the initial load.. and I have it call refreshHandler(); THIS ALSO WORKS! I can see it in the console the numbers, the datas, they are here!!!! But…. the page…. does not render the new data…… and now I’m past being mad, sad, rage, and a failure.

I come here… to stackoverflow…. for answers… and abuse.

import "./Card.css";
import { Row, Col, Container, Button } from "react-bootstrap";
import { useState, useEffect } from "react";

const Card = (props) => {
  const coinData = props.tickerSymbol;
  const [coins, setCoins] = useState([props.tickerSymbol]);
  const classes = "card " + props.className;

  const refreshHandler = async () => {
    coinData.forEach((coin) => {
      const ApiUrl = `https://api.coingecko.com/api/v3/simple/price?ids=${coin.name}&vs_currencies=usd`;
      var xhr = new XMLHttpRequest();

      xhr.addEventListener("load", () => {
        // console.log(xhr.responseText);
        let response = JSON.parse(xhr.responseText);
        let price = {};

        for (var r in response) {
          price = response[r];
          coin.price = price.usd;
        }
        console.log(coin.price);
      });
      xhr.open("GET", ApiUrl);
      xhr.send();
    });
    const ImCrazy = coinData;
    setCoins([...ImCrazy]);
  };

  useEffect(async () => {
    await refreshHandler();
  }, []);

  return (
    <div className={classes}>
      <Container>
        <Row>
          <Col xs={3}>
            <h4>Coin</h4>
          </Col>
          <Col xs={3}>
            <h4>Amount</h4>
          </Col>
          <Col xs={3}>
            <h4>Price</h4>
          </Col>
          <Col xs={3}>
            <h4>USD</h4>
          </Col>
        </Row>
        {coins.map((coins) => {
          return (
            <Row>
              <Col xs={3}>{coins.name}</Col>
              <Col xs={3}>{coins.amount}</Col>
              <Col xs={3}>{coins.price}</Col>
              <Col xs={3}>{(coins.amount * coins.price).toFixed(2)}</Col>
              {console.log(coins.price + "  I'm in the render ")}
            </Row>
          );
        })}
      </Container>
      {props.children}
      <br />
      <Button
        onClick={() => {
          refreshHandler();
        }}
      >
        Refresh
      </Button>
    </div>
  );
};
export default Card;

Please tell me what I am to blind to see. I beg of you.

Source: JavaSript – Stack Overflow

November 30, 2021
Category : News
Tags: javascript | react hooks | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.