I want to push an item in a list if its not there . If the item already in the list then remove that item

Viewed 79

I want to push an item to the list if its not previously included there. If its there then remove that item. I am able to do the first part, but no idea about how to remove that.

 handleCityCheckbox = (param1) => {
    var { cityList = [] } = this.state;
      //if cityList doesnt have param1
    if (!cityList.includes(param1)) {
      cityList.push(param1);
      this.setState({ cityList });
    } else  {
      
    }
    this.setState({ cityList });
  };

what will be the else part?

2 Answers
handleCityCheckbox = (param1) => {
    const { cityList = [] } = this.state;
    const itemIndex = cityList.indexOf(param1);
    if (itemIndex === -1)) {
      cityList.push(param1);
    } else  {
      cityList = cityList.filter((e, index) => index !== itemIndex)
    }
    this.setState({ cityList });
  };

Finished App:

enter image description here

Filtering function:

 const handleSubmit = (event) => {
    event.preventDefault();
    if (!name) {
      alert("Enter the city name");
      return;
    }
    let tempList = cities.filter(
      (city) => city.toLowerCase() !== name.toLowerCase()
    );

    if (tempList.length === cities.length) {
      tempList.push(name);
      setCities(tempList);
      return;
    } else {
      setCities(tempList);
    }
  };

In the above function, we will, first of all, use filter function to filter out i.e. delete the city name if it exists and assign it to tempList, then we compare the size of tempList with main cities list, if it's same then it indicates that the city name was not present in the main list so we will push that name to tempList and update the cities state with modified tempList, else, we just set the filtered out tempList.

Full Example :


import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [cities, setCities] = useState(["Pune", "Delhi"]);
  const [name, setName] = useState("");
  const handleSubmit = (event) => {
    event.preventDefault();
    if (!name) {
      alert("Enter the city name");
      return;
    }
    let tempList = cities.filter(
      (city) => city.toLowerCase() !== name.toLowerCase()
    );

    if (tempList.length === cities.length) {
      tempList.push(name);
      setCities(tempList);
      return;
    } else {
      setCities(tempList);
    }
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input onChange={(event) => setName(event.target.value)} />
        <button type="submit">Submit</button>
      </form>
      {cities.map((city) => (
        <p>{city}</p>
      ))}
    </div>
  );
}

Codesandbox Link

Related