i have this function in useEffect
which fetch posts from database and then set posts
state then sending them to Posts
component, i put the posts
state in the useEffect
dependency, so if a new post is created by user, the Posts
component re-render so the user doesn't need to refresh the page and it worked fine !!
but i noticed at the network tab, requests to http://localhost:8000/home/${user._id}
are being sent infinitely, i don't know why is that happening
const [posts, setPosts] = useState([]);
const { user, isLoading, error } = useContext(AuthContext);
useEffect(() => {
const getPosts = async () => {
const response = id
? await fetch(`http://localhost:8000/${id}`)
: await fetch(`http://localhost:8000/home/${user._id}`);
const data = await response.json();
setPosts(
data.sort((p1, p2) => {
return new Date(p2.createdAt) - new Date(p1.createdAt);
})
);
};
getPosts();
}, [user, id, user?._id, posts]);
return (
<div>
{posts.map((post) => (
<Posts key={post._id} post={post} />
))}
</div>
);