This part of my code shows a Skeleton
which is a placeholder preview for CardMedia
.
{loading ? (
<Skeleton
variant="rectangular"
width={308}
height={420}
animation="wave"
/>
) : (
<CardMedia
sx={{ height: 420 }}
image={item.itemMainPic}
title="green iguana"
/>
)}
I'm showing the Skeleton
when the loading
is true
and using useEffect
after 3 seconds I setLoading(false)
:
useEffect(() => {
setTimeout(() => {
setLoading(false);
}, 3000);
}, []);
const [loading, setLoading] = useState(true);
I have other CardMedia
s that I can show them using the pagination:
const handleChange = (event, value) => {
setCurrentpage(value);
};
<Pagination
count={Math.ceil(Myjson.length / postsPerpage)}
onChange={handleChange}
/>
But when I click on different pagination buttons, it no longer shows a Skeleton
, so that means I have to reload the window, in other words the useEffect
works only once and when I load other cards using pagination there is no Skeleton
.
Is there a way to show Skeleton
whenever I click on pagination buttons and then disable it after 3 seconds?
Since the code was too long, I simplified it.
CodePudding user response:
If I understand the question correctly you are basically wanting to render the skeleton on the initial component mount and any time the currentPage
state updates. For this I believe you can add currentPage
as a dependency to the useEffect
hook.
Example:
const [currentPage, setCurrentPage] = React.useState(....);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
const timer = setTimeout(() => {
setLoading(false);
}, 3000);
// Return cleanup function to clear timer if currentPage updates
// or the component unmounts prior to timeout expiring.
return () => {
clearTimeout(timer);
};
}, [currentPage]);
...