Home > Enterprise >  If - else statement not appropriately working in ReactJS
If - else statement not appropriately working in ReactJS

Time:11-13

I am displaying some data from an api using the If - else condition whereby the data should be loaded, and if nothing is found, a No data Found text should be displayed

But the problem is, the No Data Found text displays immediately the page is opened. It doesn't wait for the whole data from the api to load to appear. And when the data is loaded is when it disappears or stays if the data is not there.

How do I make the No Data Found text appear only after the data is loaded and verified to be null. Thanks.

Here is my code...

var showFarmList = '';
    if (farmCount >= 1) {
        showFarmList = user.farm.map((farm) => {
            return (
                <div className="col-6" key={farm.farmid}>
                    <div className="card card-dull card-height">
                        <Link to={`/farm-details/${user.username}/${farm.farmid}`}>

                            <div className="card-body">
                                <div className="farms-card">
                                    <h5 className="card-title title-small truncate-1">{farm.farmname}</h5>

                                </div>
                                <p className="card-text truncate-3">{farm.county.countydescription}
                                </p>

                            </div>
                        </Link>
                    </div>
                </div>
            )
        });
    }
    else {
        showFarmList =
        <>
                <div className='row'>
                    No Data Found
                </div>
            </> 
    }

    return (
        <>
            <div className="appHeader no-border transparent position-absolute">
                <div className="left">
                    <a onClick={() => navigate(-1)} className="headerButton goBack">
                        <i className="fi fi-rr-cross"></i> </a>
                </div>
                <div className="pageTitle"></div>
            </div>
            <div id="appCapsule" className="mt-2">
                <div className="section my-farmlist">
                    <h2>My Farms</h2>
                    <p className="my-farmtext">Here is a list of all the Farms you have registered on Tunda Care</p>

                    <div className="row">
                        {isLoading && <CardSkeleton cards={2} />}

                        {showFarmList}

                    </div>
                </div>
            </div>

        </>
    );
}
export default MyFarmList;

And here is the output.enter image description here

CodePudding user response:

I think this is what you expecting if I understood correctly. Add !isLoading && to second part.

 <div className="row">
                        {isLoading && <CardSkeleton cards={2} />}

                        {!isLoading && showFarmList}

                    </div>
  • Related