Home > Software design >  Code Execute First Before the data is Fetching in react js
Code Execute First Before the data is Fetching in react js

Time:10-14

I have a condition where I fetch data from API which take 8 seconds to respond in the first use effect and in the second use effect I want to use that data but the problem is that code executes first before the data is fetching and I don't have data in the second use effect

import React, { useState, useEffect } from "react";
import { Col, Container, Row } from "react-bootstrap";
import Bluecard from "../../components/bluecard/Bluecard";
import Linechart from "../../charts/linechart/Linechart";
import Solar_1 from "../../assets/images/Solar_1.png";
import Solar_2 from "../../assets/images/Solar_2.png";
import Solar_3 from "../../assets/images/Solar_3.png";
import Solar_4 from "../../assets/images/Solar_4.png";
import Solar_5 from "../../assets/images/Solar_5.png";
import Solar_6 from "../../assets/images/Solar_6.png";
import Solar_7 from "../../assets/images/Solar_7.png";
import Solar_8 from "../../assets/images/Solar_8.png";

function Solarcopy() {
    // ================ First Blue Card Data =======================//
    const [isLoading, setIsLoading] = useState(true);
    const [blueCardData, setBlueCardData] = useState([]);
    const [lineData, setLineData] = useState({
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    datasets: [
        {
        label: "Users Gained",
        data: [10, 20, 30, 10, 15, 30],
        backgroundColor: [
            "rgba(75,192,192,1)",
            "#ecf0f1",
            "#50AF95",
            "#f3ba2f",
            "#2a71d0",
        ],
        borderColor: "black",
        borderWidth: 2,
        fill: true,
        },
    ],
    });
    // useEffect(() => {
    //   const fetchdata = async () => {
    //     const response = await fetch("http://192.168.18.21:8000/performance/solar-overview/")
    //     .then((response)=>{
    //       if (!response.ok) {throw new Error("Error in fetching");} 
    //       else {return response.json;}
    //     })
    //     console.log(response)
    //   };
    // }, []);
    useEffect(() => {
    let dataValues = fetch(
        "http://192.168.18.21:8000/performance/solar-overview/"
    )
        .then((dataValues) => dataValues.json())
        .then((dataValues) => {
        // console.log(dataValues)
        setBlueCardData(dataValues);
        setIsLoading(false);
        });
    }, []);
    // ================ First Blue Card Data =======================//

    // ================ First Linechart Data =======================//
    useEffect(() => {
    const arr3 = [];
    const arr4 = [];
    if (!isLoading) {
        blueCardData.pr_hourly.time.map((item) => {
        arr4.push(item.time);
        });
        blueCardData.pr_hourly.pr_hourly.map((item) => {
        arr4.push(item.pr_hourly);
        });
    } else {
        console.log("API Data Loading");
        console.log(arr3);
        setIsLoading(true);
    }

    // fetch("https://jsonplaceholder.typicode.com/users?_limit=5")
    //   .then((response) => response.json())
    //   .then((json) => {
    // arr3 = blueCardData.pr_hourly.time;
    // console.log(arr3)
    // blueCardData.pr_hourly.pr_hourly.map((item) => {
    //   arr4.push(item.pr_hourly);
    // });

    setLineData({
        labels: arr3,
        datasets: [
        {
            label: "Values",
            data: arr4,
            backgroundColor: [
            "rgba(75,192,192,1)",
            "#ecf0f1",
            "#50AF95",
            "#f3ba2f",
            "#2a71d0",
            ],
            borderColor: "black",
            borderWidth: 2,
            fill: true,
        },
        ],
    });
    //   });
    }, []);
    // ================ First Linechart Data =======================//
    // ================== API Response Validation ====================//
    if (isLoading) {
    return <p>Loading Data</p>;
    }
    // ================== API Response Validation ====================//
    return (
    <>
        <section>
        <Container fluid>
            <Row>
            <Col lg={6}>
                <Row>
                <Col xl={6} className="mt-3">
                    <Bluecard
                    heading={blueCardData.today_revenue}
                    spanText={"PKR"}
                    text={"Today's Revenue"}
                    image={Solar_1}
                    />
                </Col>
                <Col xl={6} className="mt-3">
                    <Bluecard
                    heading={blueCardData.cuf}
                    spanText={"%"}
                    text={"CUF"}
                    image={Solar_2}
                    />
                </Col>
                <Col xl={6} className="mt-3">
                    <Bluecard
                    heading={blueCardData.total_yield}
                    spanText={"KWH"}
                    text={"Today's Yield"}
                    image={Solar_3}
                    />
                </Col>
                <Col xl={6} className="mt-3">
                    <Bluecard
                    heading={blueCardData.cuf}
                    spanText={"%"}
                    text={"CUF"}
                    image={Solar_4}
                    />
                </Col>
                <Col xl={6} className="mt-3">
                    <Bluecard
                    heading={blueCardData.system_size}
                    spanText={"kW"}
                    text={"System Size"}
                    image={Solar_5}
                    />
                </Col>
                <Col xl={6} className="mt-3">
                    <Bluecard
                    heading={blueCardData.inverters}
                    spanText={""}
                    text={"Number Of Inverters"}
                    image={Solar_6}
                    />
                </Col>
                <Col xl={6} className="mt-3">
                    <Bluecard
                    heading={blueCardData.performance_ratio}
                    spanText={"%"}
                    text={"Performance Ratio"}
                    image={Solar_7}
                    />
                </Col>
                <Col xl={6} className="mt-3">
                    <Bluecard
                    heading={blueCardData.tc_performance_ratio}
                    spanText={"%"}
                    text={"TCPR"}
                    image={Solar_8}
                    />
                </Col>
                {/* {blueCardData.map((item) => (
                    <Col xl={6} key={item.id}>
                    <Bluecard
                        heading={item.id}
                        spanText={item.albumId}
                        text={item.title}
                        image={item.thumbnailUrl}
                    />
                    </Col>
                ))} */}
                </Row>
            </Col>
            </Row>
        </Container>
        </section>
        <section className="mt-lg-5 mt-5">
        <Container fluid>
            <Row>
            <Col lg={6}>
                <Linechart chartData={lineData} />
            </Col>
            </Row>
        </Container>
        </section>
    </>
    );
}

export default Solarcopy;

see the img for code

CodePudding user response:

don't use two useEffect with the same dependency array ([]) due to this your code is executing without waiting. Instead of that combine logic of two useEffect into one also you can you async/await instead of promises syntax , it will be more readable

CodePudding user response:

if u use useeffect with ([]) it will only work in the first load. if you want to make it work second useeffect when isLoading false, use it ([isLoading]) in that case everytime isLoading change the second useEffect will work again.

  • Related