Home > OS >  How can I map through an array of objects, remove one and set my state as the new array in react-nat
How can I map through an array of objects, remove one and set my state as the new array in react-nat

Time:10-23

I have a list of checkboxes representing calendars. When a checkbox is clicked, the respective calendar is added to my state checkedTaskList as an array.

How can I map through this checkedTaskList array, and remove a calendar from it when it is unchecked? I wish to then set my state with the new array with the unchecked calendar removed.

STATE

const [checkedTaskList, setCheckedTaskList] = useState([]);

CALENDAR CHECKBOXES

<CheckBox_1 checked={() => setTaskCheked(calendar)} /> //Holidays
<CheckBox_1 checked={() => setTaskCheked(calendar)} /> //Birthdays
<CheckBox_1 checked={() => setTaskCheked(calendar)} /> //Events

setTaskCheked FUNCTION

const setTaskCheked = (calendar) => {
    if (checkedTaskList.length > 0) { //CHECK IF ARRAY IS EMPTY
     
      const tempCalendarList = checkedTaskList;
      tempCalendarList.map((cal) => {
        if (cal === calendar) { //CHECK IF SELECTED CALENDAR IS ALREADY IN checkedTaskList STATE
          const index = tempCalendarList.indexOf(cal);
          tempCalendarList.slice(index, 1);//REMOVED UNCHECKED CALAENDAR
          setCheckedTaskList(tempCalendarList);//SET STATE WITH NEW ARRAY WITH REMOVED CALENDAR
          
          
        }
        
      });
    } else {
      setCheckedTaskList([...checkedTaskList, calendar]);
    }
  };

HERE IS THE ENTIRE FILE

imports...

export default function AddCalendarModal(props) {
  const [priority, setPriority] = useState(false);
  const [checkedTaskList, setCheckedTaskList] = useState([]);

  useEffect(() => {
     if (checkedTaskList.length > 0) alert(checkedTaskList.length);
  }, [checkedTaskList]);

  const setTaskCheked = (calendar) => {
    if (checkedTaskList.length > 0) {
      if (c === true) {
        console.log(checkedTaskList.filter((cal) => cal != calendar));
        setCheckedTaskList(checkedTaskList.filter((cal) => cal != calendar));
      }
    } else {
      setCheckedTaskList([...checkedTaskList, calendar]);
    }
  };

  console.log("CHECKED TASKS"   JSON.stringify(checkedTaskList));
  console.log("CHEKCED TASKS LENGTH"   checkedTaskList.length);
  return (
    // <Modal visible={true} style={styles.container}>
    <View style={styles.container}>
      <TouchableOpacity onPress={props.clicked}>
        <Image source={require(".././assets/canceladdcalendar.png")} />
      </TouchableOpacity>
      <View style={{ top: "10%" }}>
        <View style={styles.headertext}>
          <Text style={{ fontSize: 24, fontWeight: "bold" }}>
            Manage Calendars
          </Text>
          <Text style={{ fontSize: 16, marginTop: "2%" }}>
            Select which calendars you’d like to see or add a new one.
          </Text>
        </View>
        <View style={{ marginTop: "5%" }}>
          {props.calendarData.map((calendar) => {
            return (
              <View key={calendar.summary} style={styles.calendaritem}>
                <CheckBox_1 checked={() => setTaskCheked(calendar)} />
                <View style={{ marginLeft: "3%" }}>
                  <Text>{calendar.summary}</Text>
                </View>
              </View>
            );
          })}
        </View>
      </View>
      <View
        style={{
          alignSelf: "center",
          position: "absolute",
          top: "50%",
        }}
      >
        <HearthButton
          backgroundcolor={"#1AA39B"}
          title={"Add a Calendar"}
          fontcolor={"white"}
          width={250}
        />
        <TouchableOpacity style={styles.deletecalendar}>
          <Text style={{ color: "#1AA39B", fontWeight: "bold" }}>
            Delete a Calendar
          </Text>
        </TouchableOpacity>
      </View>
    </View>
    
  );
}

styles...

CodePudding user response:

You can use Array.prototype.filter() to get all other elements.

const setTaskCheked = (calendar) => {
    if (checkedTaskList.length > 0) {
      setCheckedTaskList(checkedTaskList.filter(cal => cal != calendar)
    } else {
      setCheckedTaskList([...checkedTaskList, calendar]);
    }
  };

CodePudding user response:

Like Balastrong said, first use filter to remove the unchecked element, which you confirmed works.

What I'm assuming you're doing next is checking the array right after setting it, sorta like

setCheckedTaskList([...checkedTaskList, calendar]);
alert(checkedTaskList.length);

and this would show you the checkedTaskList's previous contents, as the call to set it is asynchronous.

EDIT: After your edit, I'm wondering what the 'c === true' is, and what it does. I rewrote the setTaskChecked a bit, and it works for me. Here's my code

const setTaskChecked = (calendar) => {
    if (checkedTaskList.indexOf(calendar) === -1) {
      console.log(calendar   " is now in array");
      setCheckedTaskList([...checkedTaskList, calendar]);
    } else {
      setCheckedTaskList(checkedTaskList.filter((cal) => cal !== calendar));
      console.log(calendar   " removed from array");
    }
  };

  useEffect(() => {
    console.log(checkedTaskList.length);
  }, [checkedTaskList]);
  • Related