skip to Main Content

I have a function which takes a long time to run, and need to implement a type of ‘loading’ message in React which displays when the function starts and goes away once it finishes.

My first idea was something along the lines of,

const myComponent = () => {

    const [isLoadingState, setIsLoadingState] = useState(false)

    // This function gets triggered whenever certain states get updated
    function verySlowFunction(): {
        setIsLoadingState(true);
        // various function calls
        // which take a long amount of time
        // here
        setIsLoadingState(false);
    }

    return (
        <h1>Our component here</h1>
        {isFetchingState ? <h5>Currently loading...</h5> : ''}
    )
}

The idea being, when the function starts, ‘isLoadingState’ becomes ‘true’, and thus the component being returned at the bottom will show as "Currently loading…", and when it gets to the last line of the function, it sets it back to ‘false’, so that h5 component goes away. (The logic has been tested and works as-expected there).

The problem I run into with this approach is that, for whatever reason, setIsloadingState doesn’t appear to be setting the component to true or false after the initial load.

Does anyone have any ideas what I might be doing wrong, or suggestions on better ways I could be doing this (without having to change the implementation of "verySlowFunction()"?

2

Answers


  1. You can use a promise to handle this situation.

    function SamplePromise() {
     var promise = new 
       Promise(function(resolve, reject) {
      //Do something 
     resolve('your result')
     });
     return promise; 
    

    Then you can call this function and use then to get your data and change the loading state. Such as

    await SamplePromise().then((data)=> 
     setIsLoadingState(false))
    

    .then() will be called when your promise finishes doing the work.

    Login or Signup to reply.
  2. React 18 introduce new hook.

    useTransition is a React Hook that lets you update the state without blocking the UI.

    You can do like below:

    function TabContainer() {
      const [isPending, startTransition] = useTransition();
      const verySlowFunction = () => {...};
    
      useEffect(() => {
        startTransition(() => {
          verySlowFunction();
        });
      }, [])
    
      return (
        <>
          <h1>Our component here</h1>
          {isPending ? <h5>Currently loading...</h5> : ""}
        </>
      );
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search