Home > database >  TypeError: undefined is not a function (near '...mockAchievements.map...')
TypeError: undefined is not a function (near '...mockAchievements.map...')

Time:06-10

I'm trying to create an individual switch for each item in the list, each item has an isEnabled that by default it has which is false, and I just want to leave it true when I click on the react native switch, but I'm getting this error whenever I try to activate or disable this switch

import {Switch} from "react-native";

const [mockAchievements, setAchievements] = useState([
    {
      isEnabled: false,
    },
    {
      isEnabled: false,
     
    }]
  function toggleSwitch(value, index) {
    setAchievements((prevAchievements) => {
      return {
        ...prevAchievements,
        [index]: {
          ...prevAchievements[index],
          isEnabled: value,
        },
      };
    });
  }
    <Switch
     trackColor={{ false: "#E9E9E9", true: "#EEF8FC" }}
     thumbColor={item.isEnabled ? "#006993" : "#CBCBCB"}
     ios_backgroundColor="#CBCBCB"
     onValueChange={(value) => {
     toggleSwitch(value, index);
     }}
                     
     value={item.isEnabled}
     />

CodePudding user response:

Use this function instead

function toggleSwitch(value, index) {
  let dat = [...mockAchievements];
  dat[index].isEnabled = value;
  setAchievements(dat)
}

and if I am not wrong, your function returns the state as an object instead of an array

  • Related