0

I have this simple PostContext in nextjs 13

'use client'

const PostsContext = createContext<PostsContextType | undefined>(undefined);

export function PostsProvider({ children }: { children: ReactNode }) {
  const [posts, setPosts] = useState<Post[]>([]);
  const [listPost, setListPost] = useState<ListPost[]>([]);

  useEffect(() => {
    console.log("fetchPosts");
    const fetchPosts = async () => {
      const { posts, listPost } = await usePostsData();
      setPosts(posts);
      setListPost(listPost);
    };

    fetchPosts();
  }, []);

  console.log("===============");

  return (
    <PostsContext.Provider value={{ posts, listPost }}>
      {children}
    </PostsContext.Provider>
  );
}

export function usePosts() {
  const context = useContext(PostsContext);
  if (!context) {
    throw new Error("usePosts must be used within a PostsProvider");
  }
  return {
    posts: context.posts,
    listPost: context.listPost,
  };
}

Already put this in the RootLayout

<PostsProvider>{children}</PostsProvider>

and then I'm using it in my Post page

export default function Post({ params }: { params: { slug: string } }) {
  const { listPost } = usePosts();
...

It return the empty listPost array and the "fetchPosts" never printed out in the log, but the "===============" is already there

Don't know how to make it work, really need help from you guys. Thank you in advance !

0 Answers0