Loading Skeleton before data totally fetched from api in react.js
I want to Load Skeleton 10 times before data totally fetched from API in react.js with the following code, but the skeleton not loading...
const snippetsdata = snippetsData.data;;
const [snippets, setSnippets] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
const timer = setTimeout(() => {
setSnippets(snippetsdata);
setLoading(false);
}, 3000);
return () => clearTimeout(timer);
}, []);
{loading && Array(10).map(()=>{
<SnippetsSkeleton />
})}
Solution 1:
When you use Array(10)
actually your map
function doesn't iterate over your array items because Array(10)
creates an array with a length of 10 but without any elements, so the indices [0]
, [1]
, ...,[9]
is not created. Instead of Array(10).map(...)
you can use Array.from , like this:
Array.from({length: 10}, (v,i)=> <SnippetsSkeleton key={i}/>)
or
Array.from(Array(10), (v,i)=> <SnippetsSkeleton key={i}/>)
Another solution to solve your problem is using Array.fill, like this:
Array(10).fill(undefined).map((v,i)=> <SnippetsSkeleton key={i}/>);