OiO.lk Blog javascript UseEffect not triggering in child component
javascript

UseEffect not triggering in child component


I have a ‘user’ object that is loaded in the parent component, and passed to this child ‘feed’ component.
However, I’m using a useEffect hook to try and load more data using that user object but the useEffect block is never triggered. testing it here with the console.log which never shows up. But even when the normal async function I use to load the ‘posts’ and ‘setLoading’ is in the block nothing happens.

it seems like the useEffect is always ignored and the "loading" and "no posts" div is always what shows up.

Child:

const Feed = ({user}: FeedProps) => {
    const [posts, setPosts] = useState<
        { text: string | null; id: string; userId: string; file: string | null; timeStamp: Date }[] | null
    >(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        console.log("fetching posts");
    }, [user]);

    console.log("posts: ", posts);

    if (loading) {
        return <div>Loading...</div>;
    }

    if (!posts || posts.length === 0) {
        return <div>No posts available.</div>; 
    }

    return (
        <div className=" border-2 border-solid border-violet-700 w-5/6 h-full">
            {posts?.map((post) => (
                <PostCard key={post.id} post={post}/>
            ))}
        </div>
    )
}

export default Feed;

Parent:

const ProfilePage = () => {

    const user = useCurrentUser();  

    return (
          {user && <Feed user={user}/>}
    )
}
export default ProfilePage;

Helper functions:

import { useSession } from "next-auth/react";

export const useCurrentUser = () => {

    const { data: session } = useSession();

    return session?.user;
};

import { db } from "@/lib/db";

export const getUserPosts = async (userId: string) => {
    try {
        const posts = await db.post.findMany({ where: { userId } });
        return posts;
    } catch (error) {
        console.error("Error fetching posts:", error);
        return null;
    }
}



You need to sign in to view this answers

Exit mobile version