Removing item from the api react hooks

function DataProfile({ weather, setWeather }) {
  const { id } = weather;
  const cityName = weather.city.name;
  const countryName = weather.city.country;
  const minTemp = weather.list[0].main.temp_min;
 

  const removeCity = (itemId) => {
    setWeather(weather.filter(({ id }) => id !== itemId));
  };

  return (
    <div>
      <div className="list">
        <button onClick={removeCity} >
          x
        </button>
        <p>
          {cityName} {countryName}
        </p>
        <p>MaxTemp : {maxTemp}</p>
      
      </div>
    </div>
  );
}

Hey, I’m trying to remove city from coming API, but I get error that filter is not a function. Anyone has idea why I get this error. I have initialized weather with useState([]).

Answer

This error just means that you’re trying to use .filter on a variable that is not an array.

Maybe the weather variable is just an object, and to remove it’s content it would be as simple as re-setting it’s state to an empty object like this:

setWeather({});

I’m assuming you did const [setWeather, weather] = useState({}) before and then assigned a value to it with setWeather(), and wish to revert it back to an empty object.

In this case, the removeCity function would look like this:

const removeCity = () => {
  setWeather({});
};

I think this works for what you need.