Transmit the timestamp information to Supabase using Next.js

Hello there! I'm facing an issue while attempting to send time data to supabase using next.js. Unfortunately, I haven't been successful in sending the data yet.

I suspect that the problem lies in the type not being valid for supabase, but I'm unsure how to resolve it.

Any guidance in the right direction would be greatly appreciated.

# 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;

Below is the query used to send the data.

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 attempted to adjust the type using new Date() but to no avail.

Answer №1

To include Date types in your code, you can convert them to strings before insertion.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The types for Cypress are not being detected by my Angular tsconfig file

I'm facing an issue with my Angular tsconfig not detecting the Cypress 12.3 types. I have tried numerous solutions to resolve this problem, but nothing seems to work, except for the extreme measure of starting the project over, which I think might sol ...

Mapbox GL JS stops displaying layers once a specific zoom level or distance threshold is reached

My map is using mapbox-gl and consists of only two layers: a marker and a circle that is centered on a specific point. The distance is dynamic, based on a predefined distance in meters. The issue I'm facing is that as I zoom in and move away from the ...

Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped. Below is the snippet in question : let item = { id: 1, name: 'chair' }; const asyncItem = timer(20 ...

Angular 4 allows for dynamically applying the active class to a clicked button, enhancing interactivity

Issue: <button *ngFor="let button of buttons" [ngClass]="{'active': isClicked}" (click)="isClicked = !isClicked" Description: A total of 10 buttons are displayed on the screen. When I click on button number 1, each button receives the clas ...

Exploring the compatibility of Next.js with jest for utilizing third-party ESM npm packages

Caught between the proverbial rock and a hard place. My app was built using: t3-stack: v6.2.1 - T3 stack Next.js: v12.3.1 jest: v29.3.1 Followed Next.js documentation for setting up jest with Rust Compiler at https://nextjs.org/docs/testing#setting-up-j ...

reusable angular elements

I'm facing a situation where I have a search text box within an Angular component that is responsible for searching a list of names. To avoid code duplication across multiple pages, I am looking to refactor this into a reusable component. What would b ...

Spacing Problem with Title Tooltips

After using the padEnd method to ensure equal spacing for the string and binding in the title, I noticed that the console displayed the string perfectly aligned with spaces, but the binded title appeared different. Is it possible for the title to support s ...

How do I disable split panel on Ionic 2 login page exclusively?

I have successfully implemented the split-pane feature in my app.html file. However, I am facing an issue where the split pane is being applied to every page such as login and SignUp. Can someone please guide me on how to restrict the split pane function ...

What is the proper way to utilize setTimeout in TypeScript?

Let's take a look at an example of how to use setTimeout in Angular and TypeScript: let timer: number = setTimeout(() => { }, 2000); However, upon compilation, you may encounter the following error message: Error TS2322: Type 'Timeout' ...

Having trouble setting up Nuxt with Typescript integration

I am venturing into the world of Typescript with Nuxt (version 2.6.1) for the first time. After creating a new project using create-nuxt-app, I followed the official guide for Typescript Support. npx create-nuxt-app my-first-app cd my-first-app npm instal ...

Best practices for transitioning a project from TypeScript 3 to TypeScript 4?

I am looking to upgrade my large monorepo, which was built using lerna, React, and TypeScript 3.7 around 2-3 years ago. My goal is to update it to TypeScript 4.8. Are there any tools available that can help me analyze and identify potential breaking chan ...

Exploring Next.js routing using "next-connect" for nested routes

In my Next.js project, I have implemented an express-like structure of route->middleware->endpoint using the next-connect package. My route patterns include: /api/tours /api/tours/:id /api/tours/top-5-cheap /api/tours/stats /api/tours/monthly-plan ...

Building a browser-like navigation system with back and forward buttons in a Next.js application

Is there a way to implement a back/forward button similar to a browser in Next.js? I attempted to achieve this functionality using the following code: const router = useRouter() router.back() // for back button // However, how can I implement a forward ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

How can you toggle the selection of a clicked element on and off?

I am struggling with the selection color of my headings which include Administration, Market, DTA. https://i.stack.imgur.com/luqeP.png The issue is that the selection color stays on Administration, even when a user clicks on another heading like Market. ...

What is the initial component that Angular will activate or run?

Uncertainty surrounds the correctness of my question. Within my application, there exist numerous routing components and feature modules. I am eager to discern whether the appcomponent.ts file or the routing logincomponent.ts file will be executed first. ...

Next js Link Button with Material-UI Enhancements

Currently, I am working on a project using Server-Side-Rendering React with Next-JS and Material-UI. I am looking to implement a button from Material UI that functions as a Link with Dynamic routes. I am having trouble figuring out how to achieve this. I ...

Problem with Jasmine in Angular 5 within Visual Studio Code

I am completely new to Angular 5 Unit testing and facing some challenges. Despite installing all @types/jasmine, I am encountering errors in my spec.ts file such as 'describle is not a name' and 'jasmine.createSpyObj does not exist on the ty ...

Issue: The Hobby plan for Next.js limits the number of Serverless Functions that can be added to a Deployment to a maximum of 12

What is considered a serverless function? I ran into an issue while deploying my website, , which has been built using Next Js for some time now. The error message that I encountered was: Error: No more than 12 Serverless Functions can be added to a Deplo ...

Scroll-triggered switching of images in a React application using Styled Components

In my Next.js application, I have implemented styled components to create a day/night mode feature based on the time of day that a user visits the site. Everything has been working well so far. However, on certain pages, I have a dark hero section, which m ...