I have created a Json file with a lot of pics of famous persons. I am importing that list and display a pic with the handleNext function. My goal now is, to get rid of that current displayed pic by deleting it from the array, so I won't get that pic again when I call the handleNext function again.
This is my code so far. I call the remove function inside the handleNext function. When i now console log the lenght of the array, it stays the same. Also the first below is a small part of the json file.
[
{
"id": 1,
"image": "img/pics/1.jpg"
},
{
"id": 2,
"image": "img/pics/2.jpg"
},
{
"id": 3,
"image": "img/pics/3.png"
},
{
"id": 4,
"image": "img/pics/4.jpg"
}
]
import images from "../Index.json"
function Celeb() {
const [image, setImage] = useState();
const [imageList, setImageList] = useState(images);
const handleNext = () => {
let random = Math.floor(Math.random() * images.length);
setImage(imageList[random].image);
const unblurit = document.querySelector(".pic img");
unblurit.classList.remove("unblur");
unblurit.classList.add("blur");
remove();
}
const remove = (id) => {
const newList = imageList.filter(image => image.id !== id);
setImageList(newList);
console.log(imageList.length);
}
const handleStart = () => {
const blurit = document.querySelector(".pic img");
blurit.classList.toggle("unblur");
}
return (
<div className='celeb'>
<div className='celeb_buttons'>
<button className='play_button' onClick={handleNext}>Next</button>
<button className='play_button' onClick={handleStart}>Start</button>
</div>
<div className='pic'>
<img src={image} />
</div>
</div>
CodePudding user response:
When you filter the array, it returns a new one, and the original remains unchanged. That's why your console.log shows always the same length. You want to log the length of the newList instead:
const remove = (id) => {
const newList = imageList.filter(image => image.id !== id);
setImageList(newList);
console.log(newList.length);
}
Edit: also, you're not calling the function using any id, so i won't remove anything. You need to call in your handleNext using remove(imageList[random].id)