I want to make a return in React that shows all posts of each user when they're logged in.
The problem is that right now, my code loads all posts of all users and only shows the posts from the current logged in user, but the others posts occupy screen space. I want to remove / not load the non logged in user posts.
I think the problem is that right now I do the verification in the JSX, but I have to do it on the map() function that load the posts, but can't find the solution by myself.
This is my code at the moment:
const posts = useSelector((state) => state.posts)
const classes = useStyles()
const user = JSON.parse(localStorage.getItem('profile'))
return (
<>
<Grid className={classes.container} container alignItems='stretch' spacing={3}>
{
posts.map((post) => (
<Grid key={post._id} item xs={12} sm={4}>
{(user?.result?.googleId === post?.creator || user?.result?._id === post?.creator) && (
<Post post={post} setCurrentId={setCurrentId}/>
)}
</Grid>
))
}
</Grid>
</>
)
And this is the output example:
Can someone help? Thanks a lot.
Here you are rendering Grid
and then checking condition so your Grid
is taking that space.
You just need to check your condition one line up before rendering Grid
Try like below:
{posts.map(
post =>
(user?.result?.googleId === post?.creator ||
user?.result?._id === post?.creator) && (
<Grid key={post._id} item xs={12} sm={4}>
<Post post={post} setCurrentId={setCurrentId} />
</Grid>
)
)}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.