The filter is not deleting each item in the array while clicking on the button. the id from onclick event is being received correctly. the first element is also being deleted then it's not deleting another element.
import React,{useState} from 'react'
export default function Tour() {
const tourPack=[
{
id:1,
name:'a'
},
{
id:2,
name:'k'
},
{
id:3,
name:'b'
}
]
const [TourPackage, setTourPackage] = useState(tourPack)
const removeTour=(id)=>{//filtering functoin
const newTour=tourPack.filter((tour)=>tour.id!==id)
console.log(newTour);
setTourPackage(newTour)
}
return (
<div>
<h1>{TourPackage.map((t)=>
<h1 key={t.id} >{t.name}<button onClick={()=>{removeTour(t.id)}}>Not interested!</button></h1>
)}</h1>
</div>
)
}
CodePudding user response:
You probably are having this problem because you have two separate variables pointing to the array when you need only one. tourPack
will be set to the default value every render cycle. And so will tourPackage
because it is based on that.
import React,{useState} from 'react'
export default function Tour() {
const [TourPackage, setTourPackage] = useState([
{
id:1,
name:'a'
},
{
id:2,
name:'k'
},
{
id:3,
name:'b'
}
]);
const removeTour=(id)=>{//filtering functoin
const newTour=TourPackage.filter((tour)=>tour.id!==id)
console.log(newTour);
setTourPackage(newTour)
}
return (
<div>
<h1>{TourPackage.map((t)=>
<h1 key={t.id} >{t.name}<button onClick={()=>{removeTour(t.id)}}>Not interested!</button></h1>
)}</h1>
</div>
)
}
Use only TourPackage
.