Home > Mobile >  Add new element to an array each time the function is called
Add new element to an array each time the function is called

Time:03-23

this is probably very easy but I'm trying to add the current weather location to an array each time the 'add to favorite' button is clicked. The location changes every time the user is searching for an other one. So each time he's looking for a new location I want the ability to add this to an array so I can after display all fav locations to a specific page. Right now each time the function is called its working but if I do it again with another location it rewrites the first one and the array remains with only 1 element. Anybody to help ?

Thanks

  let arr = [];

  const favCity = () => {
    debugger;
    let newArr = [...arr];
    let favCity = weatherSelector.weatherInfo.location.name;
    newArr.push(favCity);
    arr.push(newArr[0]);
  };




<div className="details">
        <div className="weather_text">
          <div className="city_tempa">
            <p className="city_name" onChange={(e) => favCity("city", e.target.value)}>
              {weatherSelector.weatherInfo.location.name}
            </p>
            <p className="city_name">, {weatherSelector.weatherInfo.location.country}</p>
            <br />
            <p className="city_temp">{Math.round(weatherSelector.weatherInfo.current.temp_c * 10) / 10}c°</p>
          </div>
          <div className="weather_icon">
            <img className="city_icon" src={weatherSelector.weatherInfo.current.condition.icon} />
            <p className="city_text">{weatherSelector.weatherInfo.current.condition.text}</p>
          </div>
          <div className="fav">
            <button className="fav_btn" onClick={favCity}>
              Add to Favorite
            </button>
          </div>
        </div>

Thanks everybody :)

CodePudding user response:

The array you need is the newArr, which contains the new locations. So you just need to assign this newArr to arr.

      let arr = [];
    
      const favCity = () => {
        let newArr = [...arr];
        let favCity = weatherSelector.weatherInfo.location.name;
        newArr.push(favCity);
        arr = newArr
      };

CodePudding user response:

Is selecting a new location reloading the page? Because your code doesnt seem to have any problems(as far as we ignore creating a new array for no reason, you can just do arr.push(favCity).

Because that would mean arr = [] will be inicialized again... if you can post minimal reproducible example (like codepen.io), that would surely clarify a few things

  • Related