store value to global variable from the foreach loop - javascript

I am trying to store value in the global variable then pass it through Axios, but I can't store it in the variable. here is my code sample.
const voteSubmit = document.querySelector('#voteSubmit');
const votevalue = document.querySelectorAll('.votting_buttons button');
let voteNum;
votevalue.forEach((btn) => {
btn.addEventListener('click', () => {
voteNum = btn.dataset.votno;
});
});
how could I store it?

Related

addEventListener returns undefined in Javascript

I want set the addEventListner value to int value,
const stringItem = window.addEventListener("click",(e) => {
const itemTarget = e.target;
const itemParent = itemTarget.parentElement.id;
const strItem = parseInt(itemParent.slice(5));
console.log(strItem);
return strItem;
}, false);
let currentItem = stringItem;
console.log(currentItem);
stringItem return undefined, but I want the strItem to be returned
I want to access the strItem value outside the addEventListener.
How do I do that?
The addEventListener returns undefined as a function (see link). You are passing a function to the addEventListener which gets called whenever you click on the window. The return value of that function will be lost. To be able to use that value outside of the function you will have to do something like this:
let stringItem;
window.addEventListener("click",(e) => {
const itemTarget = e.target;
const itemParent = itemTarget.parentElement.id;
const strItem = parseInt(itemParent.slice(5));
console.log(strItem);
stringItem = strItem;
return strItem;
}, false);
The last two line of your code wouldn't work as they're executed as soon as the eventListener gets added. The currentItem will always be undefined. I would advise you to read more on using callback function in javascript.
The return value of the callback function is discarded. It doesn't make sense to return anything. window.addEventListener doesn't return anything. It doesn't make sense to store the result in a variable stringItem.
You can create a variable outside of the function and store the value in it:
let value = 0;
document.querySelector('#button1').addEventListener("click",(e) => {
++value;
}, false);
document.querySelector('#button2').addEventListener("click",(e) => {
value = 0;
}, false);
document.querySelector('#button3').addEventListener("click",(e) => {
console.log(value);
}, false);
<button id="button1">Increment</button>
<button id="button2">Reset</button>
<button id="button3">Show</button>

Updating global variable value REACT.JS

The function 'clicknode' seems to successfully update the variable 'selected' as desired but when I try to access the variable from another function it still shows as empty.
let selected=[]
const clickNode = (id) => {
console.log(`${id} clicked!`);
if(selected.includes(id)){
for(let i=0;i<selected.length;i++){
if(selected[i]===id){
selected.splice(i,1);}
}
}
else{ selected.push(id)}
console.log(selected);
}

How to update value returned by function React (useState implementation)

Let's say I have such a thing, function returning value and setter Function, how Can I implement the setter function correctly to update returned value , every time it is called? (like useState's returned value and the updater function)
const myFunction = (initialValue) => {
let value = initialValue;
const setterFunction = (newValue) =>{
value= newValue;
}
forceRerender() //function that forces re-renders
return [value,setterFunction];
}
const [myValue,updaterFunc] = myFunction('someValue');
updaterFunc('newValue'); // myValue's new Value should be 'newValue'
If you're trying to re-implement how React does it, you would have to have setter functions result in the whole block running again - something like the following:
const state = [];
const App = () => {
let stateIndex = 0; // This variable keeps track of the sequential calls to `myFunction`
// (Needed if myFunction gets called multiple times)
const myFunction = (initialValue) => {
// Assign initial value if it doesn't exist yet
if (!state.hasOwnProperty(stateIndex)) state[stateIndex] = initialValue;
const value = state[stateIndex];
// Need to create a closure over the current state index...
const closureStateIndex = stateIndex;
const setterFunction = (newValue) => {
state[closureStateIndex] = newValue;
// Re-run the entire function asynchronously:
setTimeout(App);
};
// Increment state index to allow for additional calls to myFunction
stateIndex++;
return [value, setterFunction];
}
const [myValue, updaterFunc] = myFunction('initialValue');
// Call updater only on initial render:
if (myValue === 'initialValue') {
updaterFunc('newValue'); // myValue's new Value should be 'newValue'
}
console.log('Rendering. Current value is:', myValue);
};
App();
That's a bit similar to how React does it.
For an example with multiple state variables, and renaming myFunction to useState:
const state = [];
const App = () => {
let stateIndex = 0;
const useState = (initialValue) => {
if (!state.hasOwnProperty(stateIndex)) state[stateIndex] = initialValue;
const value = state[stateIndex];
const closureStateIndex = stateIndex;
const setterFunction = (newValue) => {
state[closureStateIndex] = newValue;
setTimeout(App);
};
stateIndex++;
return [value, setterFunction];
}
const [name, setName] = useState('bob');
const [age, setAge] = useState(5);
if (age === 5) {
setAge(10);
}
console.log('Rendering. Current name and age is:', name, age);
};
App();

Remove an object's key and value using a variable from function

Hey I'm trying to remove a key:value pair from state inside a Javascript Object.
It works when I hardcode the key name in the code, but when I try to use a variable from a function call, it does nothing.
Can somebody help me out?
Here's an object example:
toppingsSelected: {
"Onion":"true",
"Mushrooms":"true",
}
This works, hardcoded:
deleteTopping = toppingName => {
const { Onion, ...withoutOnion } = toppingsSelected;
console.log(withoutOnion); // Returns object without onion
};
This doesn't work:
deleteTopping = toppingName => {
const toppingName = "Onion"; // Variable gets passed in
const { toppingName, ...withoutOnion } = toppingsSelected;
console.log(withoutOnion); // Returns original object, no change made
};
So I'm basically trying to remove a key from React state but I'm pretty new to Javascript.
How can I make Javascript aware that toppingName is a key?
Another option is to add square brackets arround toppingName, and assign it to a variable. As #Bergi pointed out in the comments, this option does not mutate toppingsSelected
const toppingsSelected = {
"Onion":"true",
"Mushrooms":"true",
};
const toppingName = "Onion";
const {
[toppingName]: topping,
...withoutOnion
} = toppingsSelected;
console.log(JSON.stringify(withoutOnion));
To set the React state, you'd then do this
this.setState({ toppingsSelected: withoutOnion })
You can use delete e.g.
delete toppingsSelected[toppingName];
One way of doing this is using Array.prototype.filter()
const _obj = {
'Onion': true,
'notOnion': false
};
const newObj = Object.keys(_obj)
.filter(key => key !== 'Onion')
.reduce((acc, cur) => ({ ...acc, cur }), {})
console.log(newObj); // { notOnion: false }
This will return a new object without the 'Onion' property

create react state name with variable reference?

i want to create state like this:
componentWillReceiveProps(nextProps) {
nextProps.columns.forEach((c) => {
const name = nextProps.columns[nextProps.columns.indexOf(c)];
this.setState({ `${name}`: (this.props.activeHeaders.indexOf(c) > -1) });
console.log(`${name}`);
});
}
I am mapping on my array columns, so each item on the array, i want to set state on them as key, is there a possibe way?
Is there a possible way?
Yes, but the way you are trying is not correct, instead of calling setState inside loop, first prepare an object with all the key-value, then pass that object to setState.
Like this:
componentWillReceiveProps(nextProps) {
let obj = {};
nextProps.columns.forEach((c, i) => {
const name = nextProps.columns[nextProps.columns.indexOf(c)];
obj[name] = this.props.activeHeaders.indexOf(c) > -1;
});
this.setState(obj);
}
Didn't get the meaning of this line:
const name = nextProps.columns[nextProps.columns.indexOf(c)];
componentWillReceiveProps(nextProps) {
nextProps.columns.forEach((c) => {
const name = nextProps.columns[nextProps.columns.indexOf(c)];
this.setState({ [name]: (this.props.activeHeaders.indexOf(c) > -1) });
console.log(`${name}`);
});
}
This should do the job

Categories

Resources