I have two functions and I am trying to call them by toggling between classes using react hooks. However, it keeps on throwing an error “TypeError: Cannot read properties of undefined
(reading 'currentTarget')"
and it references this – const element = e.currentTarget;
e.target.value is a string
This is the state
const [color, setColor] = useState(false)
The function to handle the toggle
function addOrRemove(e) {
const element = e.currentTarget;
setColor(!color)
if (color){
addValue(element)
} else {
removeValue(element)
}
}
the button that calls the function
<button
id="btn"
onClick={addOrRemove()}
className={color? "red": "white"}/>
the two functions being called
function addValue(e) {
if (e.target.value !== "") {
if (!favs.includes(e.target.value)) {
favs.push(e.target.value);
localStorage.setItem("name", JSON.stringify(favs));
console.log(favs);
document.getElementById("favsarray").innerHTML = favs
}
}
}
function removeValue(e, value) {
if (e.target.value !== "") {
//delete from array
favs.pop(e.target.value);
console.log(favs);
//change the div text
document.getElementById("favsarray").innerHTML = favs;
//get the values from localstorage- parse
const stored = JSON.parse(localStorage.getItem("name"));
//delete the value
delete stored[(value, e.target.value)];
//store the new array as a string
localStorage.setItem("name", JSON.stringify(favs));
console.log(stored);
}
}