typescriptnext.jstimesupabasedayjs

Send the time data to supabase with nextjs


Hello I'm trying to send the time data to supabase with next.js, however I haven't been able to send it.

I think the cause is that the type is not valid to send it to supabase but I don't know how to fix it.

I would be very grateful if someone could point me in the right direction.

# event-form.tsx

"use client";

import { useState, useEffect } from "react";
import {
  Box,
  TextField,
  Button,
  Checkbox,
  Container,
  Grid,
} from "@mui/material";
import { publishEvent } from "../../utils/supabaseFunction";
import { useRouter } from "next/navigation";
import Link from "next/link";
import dayjs from "dayjs";
import { Session } from "@supabase/auth-helpers-nextjs";
import { supabase } from "@/utils/supabase";
import { start } from "repl";

const EventForm = ({ session }: { session: Session | null }) => {
  const router = useRouter();
  const [title, setTitle] = useState<string>("");
  const [description, setDescription] = useState<string>("");
  const [date, setDate] = useState<Date | undefined>();
  const [start_time, setStart_time] = useState<Date | undefined>();
  const [capacity, setCapacity] = useState<string>("");
  const [host_id, setHost_id] = useState<string>("");
  const [is_published, setIs_Published] = useState<boolean>(false);

  const user = session?.user;
  useEffect(() => {
    const fetchUserId = async () => {
      try {
        const { data: users, error } = await supabase
          .from("profiles")
          .select(`id`)
          .eq("id", user?.id)
          .single();
        if (error) {
          throw error;
        }
        setHost_id(users.id);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };
    fetchUserId();
  }, []);

  console.log(start_time);

  const handlePublishEvent = async (e: any) => {
    e.preventDefault();
    await publishEvent(
      title,
      description,
      capacity,
      date,
      start_time,
      host_id,
      is_published
    );
    router.push("/event");
  };

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setIs_Published(event.target.checked);
  };

  return (
    <>
      <div>
        <Container component="main" maxWidth="xs">
          {" "}
          <Box component="form" onSubmit={(e) => handlePublishEvent(e)}>
            <Grid item xs={12}>
              <TextField
                type="text"
                name="title"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                type="text"
                name="description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                type="date"
                name="date"
                value={dayjs(date).format("YYYY-MM-DD")}
                onChange={(e) => setDate(new Date(e.target.value))}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                type="time"
                name="time"
                value={dayjs(date).format("HH:mm:ss")}
                onChange={(e) => setStart_time(new Date(e.target.value))}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                type="text"
                name="capacity"
                value={capacity}
                onChange={(e) => setCapacity(e.target.value)}
              />
            </Grid>
            <Checkbox
              checked={is_published}
              onChange={handleChange}
              inputProps={{ "aria-label": "controlled" }}
            />
            Check
            <div>
              <div>
                <Button variant="contained" type="submit">
                  {is_published == true ? <>Publish</> : <>Save</>}
                </Button>
              </div>
              <div>
                <Button variant="text">
                  <Link href="/event">Back</Link>
                </Button>
              </div>
            </div>
          </Box>
        </Container>
      </div>
    </>
  );
};

export default EventForm;

And the query to send the data is below.

export const publishEvent = async (
  title: string,
  description: string,
  capacity: string,
  date: Date | undefined,
  start_time: Date | undefined,
  host_id: string,
  is_published: boolean
) => {
  await supabase.from("events").insert({
    title: title,
    description: description,
    capacity: capacity,
    date: date,
    start_time: start_time,
    host_id: host_id,
    is_published: is_published,
  });
};

I tried to change the type with new Date () but it doesn't work.


Solution

  • You can insert Date types by converting them to string.

    export const publishEvent = async (
      title: string,
      description: string,
      capacity: string,
      date: Date | undefined,
      start_time: Date | undefined,
      host_id: string,
      is_published: boolean
    ) => {
      await supabase.from("events").insert({
        title: title,
        description: description,
        capacity: capacity,
        date: date.toISOString(),
        start_time: start_time.toISOString(),
        host_id: host_id,
        is_published: is_published,
      });
    };