FriedrichGLX
FriedrichGLX

Reputation: 151

How to use Formik with React-Select with isMulti?

I'm building a system where we can create a project and assign it to several users by filling up a form using Formik, Yup and React-Select.

However, I'm really struggling with passing the array of users when submitting my form using Formik, Formik doesn't receive the data from React-Select.

Here are snippets of the code:

const validationSchema = () => {
return Yup.object().shape({
  title: Yup.string().required('A title is required'),
  description: Yup.string().required('A description is required'),
  assigned: Yup.array().required('At least one assigned user is required'),
});
  };

  const formik = useFormik({
    initialValues: {
      title: '',
      description: '',
      assigned: [],
    },
    validationSchema,
    validateOnBlur: false,
    validateOnChange: false,
    onSubmit: (data) => {
      ProjectService.create(data).then(() => {
        navigate('/projects');
        window.location.reload();
      });
    },
  });

The component containing the options to select:

Assign to:
    <SelectList
      name="users"
      options={convertToReactSelectObject(users)}
      onChange={(assignedUsers) =>
        formik.setFieldValue('assigned', assignedUsers.value)
      }
      value={formik.values.assigned}
    />
    {formik.errors.assigned ? formik.errors.assigned : null}

Does someone have an idea of what I should fix to make it work?

Thank you!

Upvotes: 1

Views: 4651

Answers (1)

FriedrichGLX
FriedrichGLX

Reputation: 151

My mistake was that I was trying to only pass the "value" field of the array to Formik which doesn't work. So I've passed the whole array of assigned users

<SelectList
      options={convertToReactSelectObject(users)}
      value={formik.values.assigned}
      onChange={(assignedUser) =>
        formik.setFieldValue('assigned', assignedUser)
      }
    />

Then on the backend, the new project will only take the value field of the assigned users.

    // Create a Project
  const project = new Project({
    title: req.body.title,
    description: req.body.description,
    assigned: req.body.assigned.map((e) => e.value),
  });

Upvotes: 2

Related Questions