I want to display a loader initially and after a certain time when the loader is turned off manually based upon the condition I want to either fun a function or display a heading 1.
I want that when initially when the page loads, the loader should be displayed but after a certain time it turns off maybe with the help of setTimeout, and if the length of the array (videoIds) is 0 I want to display the heading "Enter at least one video in the collection first" otherwise if the length is not zero then run fetchFunc() and display result and thus render component.
I tried using promises but "Enter at least one video in the collection first" is already getting rendered when the page is loading. How can I achieve it?
const [display, setdisplay] = useState();
const [userMsg, setuserMsg] = useState(true);
useEffect(() => {
displayFunc();
}, []);
function displayFunc() {
new Promise(function (myResolve) {
myResolve(
setTimeout(() => {
setuserMsg(false);
}, 2000)
);
}).then(() => {
if (videoIds.length === 0) {
setdisplay(false);
} else {
fetchFunc();
setTimeout(() => {
setdisplay(true);
}, 2000);
}
});
}
{userMsg && <Loading />}
{display ? (
<ExploreCard videoArray={videoArray} explVidFunc={explVidFunc} />
) : (
<h1>Enter at least one video in collection first</h1>
)}
CodePudding user response:
export const View = () => {
const [videos, setVideos] = useState([]);
const fetch = async () => {
// fetch logic here
setVideos(); // put response or data here
});
useEffect(() => {
/*
I don't believe the timeout is necessary, but if you want to
delay the fetch function, you can do something like the following.
setTimeout(() => fetch(), 3000);
*/
fetch();
}, [videos]);
return (
<>
{!!videos.length && <Loading />}
{!videos.length ? (
<ExploreCard
{/* explVidFunc={explVidFunc */}
videoArray={videoArray}
/>
) : (
<h1>Enter at least one video in collection first</h1>
)}
</>
);
}:
CodePudding user response:
const [loading, setLoading] = useState(false)
const [videos, setVideos] = useState([])
const fetchVideos = async () => {
try{
// call api to fetch videos
const res = callApi()
setLoading(false)
// change according to you response
setVideos(res.data)
} catch{
setLoading(false)
}
}
useEffect(() => {
fetchVideos()
},[])
Now, you can check for loading . If its true, show Loader else, check for videos. If its length is zero show some component else show different component.