Next.js Discord

Discord Forum

Controlled <Select> not working as expected

Unanswered
Havana posted this in #help-forum
Open in Discord
HavanaOP
Afternoon all.

I have a simple form in nextjs, as seen below. Shadcn + react-hook-form is used, and i'm trying to set an object into state.

The issue is that on setting state in the select handler, it sets then seemingly renders again, setting selectedClient back to undefined.

I'm sure this isn't an issue with shadcn or radix, so does anybody have an idea of what i'm doing wrong?

5 Replies

HavanaOP
<Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)}>
                    <div className='m-12'>
                        <FormField
                            control={form.control}
                            name="clientId"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Client</FormLabel>
                                    <Select
                                        onValueChange={(value) => {
                                            const client = clients.find((client: any) => client.client_id === value)
                                            console.log(client);
                                            setSelectedClient(client)
                                        }}
                                        value={selectedClient?.client_id}
                                    >
                                        <FormControl>
                                            <SelectTrigger>
                                                <SelectValue />
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            <SelectGroup>
                                                <SelectLabel>Client</SelectLabel>
                                                {clients?.map((client: any) => (
                                                    <SelectItem key={client.client_id} value={client.client_id}>
                                                        {`${client.client_forename} ${client.client_surname}`}
                                                    </SelectItem>
                                                ))}
                                     
                            )}
                        />
Siberian
even tho you are setting onValueChange and value yourself I'd guess this is some sort of colission between your own state and that of react hook form
is there any reason you're not using RHF to manage state for this?
Cause typically you'd call field.onChange (with the field you're getting from render in FormField)
and if you need that state yourself you could use RHFs getValue() or watch()