0

I am using react select https://www.npmjs.com/package/react-select with react-hook-form and this is my code:

import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as Yup from "yup";
import Select from "react-select";

export function App() {
  const schema = Yup.object({
    name: Yup.string().required().min(3).max(191).label("Collection Name"),
    marketplaces: Yup.mixed().nullable().label("Marketplaces")
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
    control
  } = useForm({
    resolver: yupResolver(schema)
  });

  const onSubmit = async (input) => {
    console.log("input", input);
  };

  const marketplace_options = [
    { label: "aut", value: 1 },
    { label: "nobis", value: 2 },
    { label: "nostrum", value: 3 },
    { label: "reprehenderit", value: 4 },
    { label: "unde", value: 5 },
    { label: "est", value: 6 },
    { label: "amet", value: 7 },
    { label: "dolores", value: 8 },
    { label: "tempora", value: 9 },
    { label: "occaecati", value: 10 },
    { label: "recusandae", value: 11 }
  ];

  const item = {
    id: 12,
    name: "test-collection",
    marketplaces: [
      {
        label: "amet",
        value: "7",
        pivot: { collection_id: 12, marketplace_id: 7 }
      },
      {
        label: "tempora",
        value: "9",
        pivot: { collection_id: 12, marketplace_id: 9 }
      }
    ]
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("name")}
        placeholder="Name"
        defaultValue={item.name}
      />
      <Controller
        name="marketplaces"
        control={control}
        render={({ field }) => (
          <Select
            {...field}
            options={marketplace_options}
            isMulti
            className="form-control w-full"
            defaultValue={item.marketplaces}
          />
        )}
      />
      <input type="submit" />
    </form>
  );
}

But, it is showing undefined while trying to submit (without changing the marketplaces), but if I change it once, then only the value will be submitted.

Codepen link

1 Answer 1

1

Solved: Fixed by moving, defaultValue from select to Controller tag. Something like:

<Controller
        name="marketplaces"
        control={control}
        defaultValue={item.marketplaces}
        render={({ field }) => (
          <Select
            {...field}
            options={marketplace_options}
            isMulti
            className="form-control w-full"
          />
        )}
      />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.