Reputation: 107
The current code displays only "Done !!!" after end work (about 3 seconds). I want to display "Done !!!" after "Loading..." first.
import React, { useState, useEffect, useCallback } from "react";
const App = () => {
const [loading, setLoading] = useState<boolean>(false);
const [workingResult, setWorkingResult] = useState<string>();
const runWorking = useCallback(async () => {
// working.... (during about 3 seconds)
var start = new Date().getTime();
while (new Date().getTime() < start + 3000);
return "Done !!!";
}, []);
const setWorking = useCallback(async () => {
setLoading(true);
setWorkingResult(await runWorking());
setLoading(false);
}, [runWorking]);
useEffect(() => {
setWorking();
}, [setWorking]);
return <div>{loading ? "Loading..." : workingResult}</div>;
};
export default App;
Upvotes: 0
Views: 641
Reputation: 107
thank you. i solved that.
const runWorking = () => new Promise(resolve => setTimeout(() => {
let returnValue:any = [];
// working...
resolve(returnValue); }, 1)
);
const setWorking = async () => {
setLoading(true);
setWorkingResult(await runWorking());
setLoading(false);
}
Upvotes: 0
Reputation: 3507
you need to use promise constructor while
will not work because async function require function that return promise so try this:
const runWorking = () =>
new Promise(resolve =>
setTimeout(() => {
resolve("done");
}, 3000)
);
const setWorking = async () => {
setLoading(true);
setWorkingResult(await runWorking());
setLoading(false);
}
here a full working example
Upvotes: 1