NextJs + Supabase“使用身份验证用户 ID 提交”

问题描述 投票:0回答:1

我正在尝试将 user.id 插入“帖子表(id 列)”来发布文章。 试了很多次都无法插入user.id!!

这是我的代码。

"use client";
import { useState } from "react";
import supabase from "@/utils/supabase/client";

export function Edit() {
  const [body, setBody] = useState("");

  const handleSubmit = async (e: { preventDefault: () => void }) => {
    e.preventDefault();

    const { data, error } = await supabase.from("posts").insert([{ body }]);
    if (data) {
      setBody("");
      window.location.reload();
    }
    if (error) {
      console.error(error);
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit} className="flex flex-col text-black">
        <label htmlFor="postsBody" className="text-white">
          Note Title:
        </label>
        <input
          id="postsBody"
          className="mt-5"
          type="text"
          value={body}
          onChange={(e) => setBody(e.target.value)}
          required
        />
        <button
          type="submit"
          className="bg-white p-3 rounded mt-5 text-black font-bold"
        >
          Add Contents
        </button>
      </form>
    </div>
  );
}

请教我如何修复此代码以实现我的目的!

forms authentication next.js supabase userid
1个回答
0
投票

将 user.id 添加到您的声明中。

您可以从这里开始:

export function Edit() {
  const [body, setBody] = useState("");
  const [userId, setUserId] = useState(null);

  useEffect(() => {
    setUserId(supabase.auth.session()?.user?.id);
  }, [supabase.auth.session()]);
© www.soinside.com 2019 - 2024. All rights reserved.