简体   繁体   中英

Pushing multiple objects in an array without overwriting other objects in TypeScript & React - Adding to a Favorites list

I am finishing a weather app in TypeScipt and React, and the last feature I need to include is the ability to add a queried location to a favorites list. This is the second-page "favorites".

Using a button on the card displayed when a location is queried sets the favorite state to true.

<button className="add-favorite btn" onClick={() => addToFavoritesHandler()}>Add to Favorites</button>

Though, when searching for a new location, the array gets mutated. And even when attempting to add a new location to your favorites, it only shows that one location, no previous locations.

This is where if there is a favorited location is mapped out.

      {favorites.length === 0 ? (
        <p> Add locations to favorites! </p>
      ) : (
        favorite &&
        arr?.map((location, id) => {
          return (

I simply want to be able to add multiple locations to the favorites list when pressing the button.

This function handles the pushing to the array and is drilled down to the button on the queried location.

const [favorite, setFavorite] = useState(true);
  let favorites: WeatherType[] = [];
  // Easier readability 
  let location = weatherData;

  // Pushing the favorite location into the favorite array
  const addToFavoritesHandler = () => {
    setFavorite(true);
    if (location && favorite && !favorites.find((o) => o === location)) {
      favorites.push(location);
    }
    return favorites;
  };

The GitHub Repo - https://github.com/carbondesigned/granular-ai-assignement-weather-app

Thank you.

I quickly read the code inside the repository and I've noticed that the favorites array isn't keep inside a useState , I think that this is the problem.

In this way that array will be recreated on every render.

If you change with:

const [favorites, setFavorites] = useState<WeatherType[]>([]);

and, inside the function addToFavoritesHandler you update favorites with:

setFavorites(favorites)

you should make this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM