timtbdev/Next.js-Blog-App

Publish the Post

cca-Parth opened this issue · 3 comments

There is no option to publish the Post, When I create a new post, the status is always in Draft, so how do I publish it?

Did u test your code?

there is no code for publishing post to posts table. Please commit latest updates..

There's a comment here with a way to publish Posts, but it looks like it has been deleted.

You can drop the Drafts table and create an Action to publish posts:

"use server";

import * as z from "zod";
import { cookies } from "next/headers";

import { createClient } from "@/utils/supabase/server";
import { postPublishSchema } from "@/lib/validation/post";

export async function PublishPost(context: z.infer<typeof postPublishSchema>) {
  const cookieStore = cookies();
  const supabase = createClient(cookieStore);
  try {
    const post = postPublishSchema.parse(context);

    const { data, error } = await supabase
      .from("posts")
      .update({
        published: post.published,
      })
      .match({ id: post.id })
      .select()
      .single();

    if (error) {
      console.error(error);
      return null;
    }
    return data;
  } catch (error) {
    console.error(error);
    return null;
  }
}

And add this function to post-edit-button.tsx

  async function publishMyPost() {
    setShowLoadingAlert(true);
    if (id && session?.user.id) {
      const myPostData = {
        id: id,
        published: true,
      };
      const response = await PublishPost(myPostData);
      if (response) {
        setShowLoadingAlert(false);
        toast.success(protectedPostConfig.successPostPublished);
        router.refresh();
      } else {
        setShowLoadingAlert(false);
        toast.error(protectedPostConfig.errorUpdate);
      }
    } else {
      setShowLoadingAlert(false);
      toast.error(protectedPostConfig.errorUpdate);
    }
  }

Remember to change the code in the create-posts.ts to .from("posts")