timtbdev / Next.js-Blog-App

✨ Multi-User, Full-stack blogging application built with Next.js and Supabase.
https://ink.mn
293 stars 42 forks source link

Publish the Post #8

Open cca-Parth opened 9 months ago

cca-Parth commented 9 months ago

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?

husleuujii commented 6 months ago

Did u test your code?

husleuujii commented 6 months ago

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

raphaelandrews commented 5 months ago

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")