What's the issue with my code ?
I've gotten two - TypeError: Cannot read properties of undefined (reading 'value')
expected behavior = click one button, the button uses class name red and calls function addValue if I click this button again it should call function removeValue and its color should change to white.
Instead I get this type error and every button is highlighted in red.
const [color, setColor] = useState(false)
function addValue(e) {
> 38 | if (e.target.value !== "") {
function removeValue(e, value) {
> 63 | if (e.target.value !== "") {
These are the functions
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);
}
}
I am calling this function with this and an event handler
function addOrRemove(e) {
const elem = e.currentTarget;
setColor(!color)
if (color){
addValue(elem)
} else {
removeValue(elem)
}
}
<button
id="btn"
onClick={addOrRemove}
className={color? "white": "red"}
value={"Name: " d.name " Description: " d.description " Stars: " d.stargazers_count " URL: " d.html_url}
CodePudding user response:
you just need to replace e.target.value
in the two offending places with e.value
.
This is because e
is the argument to the function, which you're calling like this:
addValue(elem);
after
const elem = e.currentTarget;
where e
is the argument to your event handler function. So elem
is the DOM element that the event handler is currently firing on, therefore this is what e
is inside the function. And DOM elements don't have a target
property, but - if they're a button or input - they do have a value
property.
It would also be clearer if you call the argument something like elem
(which you use when you make the call) or element
(in full) rather than e
, which by convention is used for an event object, and may be what is confusing you here.