Home > Software engineering >  Checked prop in MUI switch is not updating
Checked prop in MUI switch is not updating

Time:12-24

RankPermission.value in switchPermission function is changing from false to true, but MUI Switch is not updating in the browser. I don't know why isn't it updating, and I didn't try much. I don't have any ideas how can I fix it.

const [activeRank, setActiveRank] = useState<FactionRanks>();

export type FactionRanks = {
  id: number;
  name: string;
  rankPermissions: FactionRanksPermissions[];
};

export type FactionRanksPermissions = {
  label: string;
  value: boolean;
};

const ActionMenu = () => {
  const { activeRank } = useContext(FactionPanelContext);

  const switchPermission = (rankPermission: FactionRanksPermissions) => {
    rankPermission.value = !rankPermission.value;
    console.log(rankPermission);
  };

  return (
    <Wrapper>
      <Buttons>
        {activeRank?.rankPermissions.map(
          (rankPermission: FactionRanksPermissions, index: number) => (
            <Row key={index}>
              <OptionDetails>{rankPermission.label}</OptionDetails>
              <IOSSwitch
                checked={rankPermission.value}
                inputProps={{ 'aria-label': 'secondary checkbox' }}
                onClick={() => switchPermission(rankPermission)}
              />
            </Row>
          )
        )}
      </Buttons>
    </Wrapper>
  );
};

CodePudding user response:

state is been set with the wrong object.

activeRank

You should be setting state with new object

rankPermission

CodePudding user response:

You are changing rankPermission in place here

rankPermission.value = !rankPermission.value;

You should be setting state, with a new object of rankPermission, where it is defined instead.

  • Related