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
You can use a promise to handle this situation.
Then you can call this function and use then to get your data and change the loading state. Such as
.then() will be called when your promise finishes doing the work.
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:
}