React: How to show Spinner & Component (at the same time) when State Changes using `useEffect`

Viewed 2494

I am using conditional Rendering to show the spinner during first API call.
And when the date changes as seen in useEffect dependency array, it makes API call again

Question:

If the data fetch is not complete, the old data is shown in the screen.
But I want the spinner to show over the old data so that a user can sense that data loading is in progress .

The current implementation i.e conditional rendering only shows one component either the spinner or the Grid.

Spinner

Before Loading

Grid component After Loading

    import React, { Component, useState, useEffect } from "react";
    import { connect } from "react-redux";
    import ApiHelper from "../../api/ApiHelper";
    import ReactDataGrid from "react-data-grid";
    import { Toolbar, Data, Filters } from "react-data-grid-addons";
    import JarvisSpinner from "../presentationalComponents/JarvisSpinner";
    import { withRouter } from "react-router-dom";
    import "../../css/styles.css";
    import "../../css/JarvisGrid.css";

    const JarvisGrid = (props) => {
      const [pagesize, setPageSize] = useState(15);
      const [data, setdata] = useState([]);
      const [filters, setFilters] = useState({
        filterfield: "Application Send",
        filtervalue: "Base",
      });
      const [sort, setSort] = useState({
        Field: "PublicOrderNumber",
        Direction: "desc",
      });
      const [loading, setloading] = useState(true);

      useEffect(() => {
        //Set data
        ReloadData();
      }, [props.uid, props.CalendarDates.fromDate, props.CalendarDates.toDate]);


      // For Loading Data using API
      const ReloadData = () => {
        ApiHelper.GetGridQueryResult(
          props.uid,
          props.filterField,
          props.filterValue,
          props.CalendarDates.fromDate,
          props.CalendarDates.toDate
        )
          .then((response) => {
            setdata(response.data.responses);
            setloading(!loading);
          })
          .catch((error) => {
            setdata([]);
            switch (error.response.status) {
              case 403:
                console.log("Error code --> " + 403);
                props.history.push("/unAuthorizedPage");
                break;
              default:
                console.log("Error String --->" + error);
            }
          });
      };

      return (
        <>
          {loading ? (
            <JarvisSpinner size="3x" />
          ) : (
            <div className="JarvisGrid">
              <ReactDataGrid
                columns={props.columns}
                rowGetter={(i) => data[i]}
                rowsCount={data.length}
                minHeight={500}
                uid={props.uid}
                enableRowSelect={null}
                enableCellSelect
                toolbar={<Toolbar enableFilter="true" />}
                onAddFilter={(filter) => {
                  setFilters({
                    filterfield: filter.column.key,
                    filtervalue: filter.filterTerm,
                  });
                }}
                onClearFilters={() =>
                  setFilters({
                    filterfield: "OrderType",
                    filtervalue: "Base",
                  })
                }
                onGridSort={(sortColumn, sortDirection) => {
                  setSort({ Field: sortColumn, Direction: sortDirection });
                }}
              />
            </div>
          )}
        </>
      );


    };
    function mapStateToProps(state) {
      return {
        CalendarDates: state.calendarDates,
      };
    }

    export default withRouter(connect(mapStateToProps)(JarvisGrid));

Please note that am using redux for state management and react-router.

================================================= After Implementing the solution provided by MwamiTovi Now I have to figure out the overlaying stuff.

After implementing solution

3 Answers

This is actually fine, based on your logic here:

// Within your "return" statement
return (
   <>
      {loading ? ( 
        <JarvisSpinner size="3x" />   // renders if `loading === true`
        ) : (
        <div className="JarvisGrid">  // renders if `loading === false`
          <ReactDataGrid .../>
        </div>
        )
      )}
   </>
)

So this is what you actually want:

  • First time, load only the spinner during API call

  • Once data fetch (API call) is a success, show only the Grid component

  • Upon subsequent API calls, render both the spinner and Grid

Let's this:

// Initiate `data` as `null`
// After the first time, `data` will never be `null` again
const [data, setdata] = useState(null);

// Remember, !null === true since data === null,
// So first time API call, only spinner will show up,
// Upon the next calls, !data === false, so this won't load
if (!data) {
  return <JarvisSpinner size="3x" /> ;
}

// Within your "return" statement
// After the first API, all the other API calls will do this...
return (
   {loading ? ( 
     <>
        <JarvisSpinner size="3x" />  // renders both spinner & component, `loading === true`
        <div className="JarvisGrid"> // consider placing an "overlay" onto the component
          <ReactDataGrid .../>
        </div>
     </>
    ) : (
        <div className="JarvisGrid">  // renders only component, when `loading === false`
          <ReactDataGrid .../>
        </div>
        )
    )}
)

I would do this in your ReloadData function:

const ReloadData = () => {
    setLoading(true); // HERE

    ApiHelper.GetGridQueryResult(
      props.uid,
      props.filterField,
      props.filterValue,
      props.CalendarDates.fromDate,
      props.CalendarDates.toDate
    )
      .then((response) => {
        setdata(response.data.responses);
        setloading(false); // HERE
      })
      .catch((error) => {
        setdata([]);
        setloading(false); // HERE

        switch (error.response.status) {
          case 403:
            console.log("Error code --> " + 403);
            props.history.push("/unAuthorizedPage");
            break;
          default:
            console.log("Error String --->" + error);
        }
      });
  };

https://www.npmjs.com/package/react-loading-overlay


Check this. I believe that this can solve your problem.

<LoadingOverlay
active={isLoading}
    spinner={Your own spinner}
    styles={{
    wrapper: {
       height: "100vh",
       overflow: "scroll"
    }
}}>
        <div>Show your content here</div>
</LoadingOverlay>
Related