Phạm Hiếu
Phạm Hiếu

Reputation: 43

Unselect MUI Multi select with initial value

I got a problem with MUI Select (multiple) inside a Formik form. Suppose that I have a task stored in database with taskName, assignTo (array of staff). Now I'm trying to make a form where I can update/change assignTo values. So the form got initialValues with:

const savedTask = {
  id: 1,
  name: "Task A",
  assignTo: [
    {
      id: 1,
      name: "Oliver Hansen",
      age: 32
    }
  ]
};

and people list

const personList = [
  {
    id: 1,
    name: "Oliver Hansen",
    age: 32
  },
  {
    id: 2,
    name: "Van Henry",
    age: 25
  },
  {
    id: 3,
    name: "Oliver",
    age: 27
  }
];

The problem is I can't unselect "Oliver Hansen" in the update form. When I click on it, it also adds one more "Oliver Hansen".

Image

Codesandbox

Did I implement wrong or that's how formik setFieldValues behaves?

Upvotes: 3

Views: 4232

Answers (2)

George Reyes
George Reyes

Reputation: 41

You can choose to set the initial value of your state to reset it. In my case I have a list and set the value to my placeholder.

const [yearFrame, setYearFrame] = React.useState<string[]>([newDate]);
const handleYearFrame = (event: SelectChangeEvent<typeof yearFrame>) => {
        const { target: { value }, } = event;
        if (value === yearFrame[0]) {
            setYearFrame(["Select Year"]);
        }
        else {
            setYearFrame(
                typeof value === 'string' ? value.split(',') : value
            );
        }
    };

In the textfield:

<FormControl style={{ width: "30vh", marginLeft: "2vh", marginTop: "2vh" }}>
  <InputLabel id="demo-multiple-name-label">Select Year</InputLabel>
    <Select
      value={yearFrame}
      onChange={handleYearFrame}
      input={<OutlinedInput label="Select Year" />}
      MenuProps={MenuProps}
    >
      {optionsYear.map((option) => {
        return (option.label === "Select Year" ? <MenuItem key= 
          {option.label} disabled value={option.label}><span style={{ color: 
          "rgb(156, 156, 156)" }}>{option.label}</span></MenuItem> : 
          <MenuItem key={option.label} value={option.label}>{option.label} 
           </MenuItem>)
         })}
   </Select>
</FormControl>

This is because I am reusing logic and have the same textfield as a multi-select so the value appears as a list. If you are not using a multi-select you can set the state to null and it will automatically render your placeholder.

Upvotes: 1

Fraction
Fraction

Reputation: 12954

From the Select API page(value prop):

...

If the value is an object it must have reference equality with the option in order to be selected. If the value is not an object, the string representation must match with the string representation of the option in order to be selected.

savedTask.assignTo and personList have different object references even if they have the same value, so you have to use Array.filter to have the initial value of assignTo from personList like this:

const initValues = { 
  ...savedTask, 
  assignTo: personList.filter(person => savedTask.assignTo.some(obj => obj.id === person.id))
};

const formik = useFormik({
  initialValues: initValues,
  onSubmit: (values) => {
    console.log("values submit ", values);
  }
});

Working example:

Edit hopeful-johnson-q75g8

Upvotes: 1

Related Questions