Shadcn using Select component inside form not setting value

203 Views Asked by At

So I am using a form component from Shadcn, which contains Input, Select and Checkboxcomponents.

The Input and Checkbox components are working fine and there are no issues with them, which makes me think its something to do with the Select component.

I have setup a FormSchema:

const formSchema = z.object({
  title: z.string().min(1),
  firstname: z.string().min(1),
  lastname: z.string().min(1),
});

I then setup the useForm hook:

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

I then have a useEffect which checks to make sure that we have got the user information from the database, if we do I set the values of the form:

useEffect(() => {
  if (dbUser) {
    form.setValue("title", dbUser.title);
    form.setValue("firstname", dbUser.firstname);
    form.setValue("lastname", dbUser.lastname);
  }
}, [dbUser]);

Now as I mentioned the firstname and lastname are inputs and this works fine, but the title is a Select component:

<FormField
    control={form.control}
    name="title"
    render={({ field }) => {
      return (
        <FormItem>
          <FormLabel>Title</FormLabel>
          <Select
            onValueChange={field.onChange}
            defaultValue={field.value}
            value={field.value}
          >
            <FormControl>
              <SelectTrigger>
                <SelectValue placeholder="Select" />
              </SelectTrigger>
            </FormControl>
            <SelectContent>
              <SelectItem value="Doctor">Doctor</SelectItem>
              <SelectItem value="Mr">Mr</SelectItem>
              <SelectItem value="Mrs">Mrs</SelectItem>
              <SelectItem value="Miss">Miss</SelectItem>
            </SelectContent>
          </Select>
          <FormMessage />
        </FormItem>
      );
    }}
  />

When debugging the issue, if I navigate to the page using a standard router.push the Select component will not populate, when I refresh the page though the Select component does select the correct value?

0

There are 0 best solutions below