'Can i populate a formik initialValue field that is an array? i'm using the react multiselect dropdown here, pls how can i do this

** const initialValues AssignClass: [],**

**NOW IN THE MULTISELECT DROP DOWN COMPONENT, i have set up formik there to my best effort, take a look **

import { ErrorMessage, useField } from "formik";
import Multiselect from "multiselect-react-dropdown";

const optionsArray = [
  { name: "Option1", id: 1 },
  { name: "Daniel", id: 2 },
];

const AppMultiSelect = ({
  label = "Assign Class(es)",
  obscure = false,
  extraClasses,
  error,
  touched,
  onFieldTouched,
  options,
  onSelect,
  onRemove,
  ...props
}) => {
  const [field, meta, helpers] = useField(props);
  console.log(helpers, " the helpers");
  return (
    <div className="flex flex-col cursor-pointer w-full z-50 p-[5px]">
      <label className="text-[14px] text-[#7D8592] font-semibold mb-2">
        {label}
      </label>
      <div className=" w-full text-[#DADADA] py-[7px] border border-[#D8E0F0]  rounded-2xl focus:border-danger focus:ring-danger  py-[12px] px-[14px]">
        <Multiselect
          options={options} // Options to display in the dropdown
          selectedValues={null} // Preselected value to persist in dropdown
          onSelect={(selectedList) => {
            helpers.setValue(...field.value, selectedList);
            console.log(selectedList, " you selected this");
          }} // Function will trigger on select event
          onRemove={(selectedItem) =>
            console.log(field.value, " to be removed")
          } // Function will trigger on remove event
          displayValue="name" // Property name to display in the dropdown options
          {...props}
        />
      </div>

      {/* {error && touched && (
        <span className="text-[14px] text-accent">{error}</span>
      )} */}
    </div>
  );
};

export default AppMultiSelect;

** so, as you see above, i'm using the setValue, but then, the field updates but it happens once, even if i keep selecting more items... thanks in advance, by the way, im doing the formik validation and the rest in another component called addTeacher, and using yup for the schema part **

AppMultiSelect
                  name="AssignClass"
                  options={[
                    { name: "fred" },
                    { name: "cere" },
                    { name: "veee" },
                    { name: "mmeee" },
                    { name: "typ" },
                    { name: "wewe" },
                  ]}
                /> 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source