Next.js Discord

Discord Forum

Trying to pass UserID to API through form. The ID is retrieved, but doesn't seem to be passed.

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
I'm making an event management application. I'm using better-auth & mongodb. I got a form in which I can create an event. Now, alongside the event name, and dates I want to pass along the owner's user-id so that we know whose events are. I'm trying to pass it through a hidden form field — it didn't work. Same with putting it in as a default value. I can get it printed to the console, but when I print the values that are sent to the API, all the values show but the ID which is shown as undefined.

NewEventForm.tsx

const formSchema = z.object({
 [...]
  owner: z.any(),
})


const { 
        data: session, 
    } = authClient.useSession() 

  const owner = (session?.user.id)?.toString()
  console.log(typeof(owner))

  const form = useForm<z.infer<typeof formSchema>>({
      resolver: zodResolver(formSchema),
      defaultValues: {
        name: "",

      },
        }
      )
  
  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    try {
      
      toast.success('work')
      console.log(values)
      await fetch('/api/events', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });
    } catch (error) {
      console.log(error);
    }
  };
  
  
  return (
    <Form {...form}>
      <form className='flex items-center justify-center space-y-8' onSubmit={form.handleSubmit(onSubmit)}>
       [...]
       <FormItem>
              <FormLabel>Start date</FormLabel>
              <FormControl>
                <Input type='hidden' name='owner' value={owner} />
              </FormControl>
              <FormMessage />
            </FormItem>
        <Button type="submit">Create</Button>
      </form>
    </Form>
  )
}

6 Replies

Spectacled bearOP
I'm still sharing code, but reached message character limit
My event model (models/Event.js)

import mongoose from 'mongoose'

const eventSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    start: {
        type: Date,
        required: true,
    },
    end: {
        type: Date,
        required: true,
    },
    owner: {
        type: mongoose.Schema.Types.Mixed,
        required: true,
    }
})

const Event = mongoose.models.Event || mongoose.model("Event", eventSchema);

export default Event
The events API
import type { NextApiRequest, NextApiResponse } from 'next'
import dbConnect from '@/lib/mongodb'
import Event from '@/models/Event';

export default async function handler(req, res) {
    await dbConnect();

    const { method } = req;

    switch (method) {
        case 'GET':
            try {
                const event = await Event.find({});
                res.status(200).json({ success: true, data: event})
            } catch (error) {
                res.status(400).json({ success: false })
                console.log(error)
            }
            break
            case 'POST':
                try {
                    const event = await Event.create(req.body)
                    res.status(201).json({ success: true, data: event })
                } catch (error) {
                    res.status(400).json({ success: false })
                    console.log(error)
                }
            break
            default:
                res.status(400).json({ success: false })
                break
    }
}
That's all i think