I am iterating through an array of objects and displaying items to the page. On button click, I would like to add the clicked item to a favourites array.
When I click on the first button multiple times the item does get added to my array multiple times. When I click on the second or third button, the item gets added but it overrides the previous items that were stored in the array. Not sure what I am doing wrong in my handleFavourites function
import React from "react";
import Tour from "./Tour";
const Tours = ({ tours }) => {
return (
<section>
<div className="title">
<h2>our tours</h2>
<div className="underline"></div>
</div>
{tours.map((tour) => {
return <Tour tour={tour} key={tour.id} />;
})}
</section>
);
};
export default Tours;
import React, { useState } from "react";
const Tour = ({ tour }) => {
const [favourites, setFavourites] = useState([]);
const handleFavourites = () => {
const clickedTour = {
tour: tour.name,
};
setFavourites([...favourites, clickedTour]);
};
console.log(favourites);
return (
<article className="single-tour">
<img alt={tour.name} src={tour.image} />
<footer>
<div className="tour-info">
<h4>{tour.name}</h4>
<h4 className="tour-price">${tour.price}</h4>
</div>
<p>{tour.info}</p>
<button onClick={handleFavourites}>Add to favourite</button>
</footer>
</article>
);
};
export default Tour;