0

I am using the useState hook and have an array of conditions

const [conditions, setConditions] = useState([])

Each element in this array contains a {condition: "some string", value: boolean}

I render my array like this:

       <FormControl component="fieldset">
            <FormGroup aria-label="position" column className={classes.form}>
              {conditions.map(({ condition, value }, index) => {
                return (
                  <FormControlLabel
                    key={index}
                    value="end"
                    control={
                      <Checkbox
                        checked={value}
                        onClick={() => {
                          changeConditionValue(index, !conditions[index].value);
                        }}
                      />
                    }
                    label={condition}
                    labelPlacement="end"
                  />
                );
              })}
            </FormGroup>
          </FormControl>

Now I am trying to change the condition´s value at a certain index if you press on the checkmark attached to it and I have set it up like this:

 const changeConditionValue = (findIndex, newValue) => {
    const saveConditions = conditions;
    setConditions([]);
    saveConditions.map(({ condition, value }, index) => {
      if (index != findIndex) {
        setConditions((old) => [...old, { condition, value }]);
      } else {
        setConditions((old) => [...old, { condition, newValue }]);
      }
    });
  };

First I save the old conditions because if I keep using the "...old" the values of the old array will be saved and I do not want that that is why I have my saveConditions where I map through in order to set those values to my new setConditions. Everything works fine, except for if I do this more than one time. The first time the value gets returned back, but the second time it returns undefined ?

This is the error: Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.
Elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled SwitchBase element for the lifetime of the component.
The nature of the state is determined during the first render, it's considered controlled if the value is not `undefined`.
```
Lucas Goldner
  • 617
  • 9
  • 29
  • Does this answer your question? [A component is changing an uncontrolled input of type text to be controlled error in ReactJS](https://stackoverflow.com/questions/47012169/a-component-is-changing-an-uncontrolled-input-of-type-text-to-be-controlled-erro) – Nik Dec 24 '20 at 14:27
  • No not really :/ – Lucas Goldner Dec 24 '20 at 14:49

1 Answers1

2

Nevermind I fixed it myself:

setConditions((old) => [...old, { condition, value: newValue }]);

not it works!

Lucas Goldner
  • 617
  • 9
  • 29