im learning react where i was confused when i came across this
const index = countertemp.indexOf(counter);
React snippet below which works:-
state = {
counters: [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 2 },
{ id: 4, value: 11 },
],
};
counter = { id: 3, value: 2 }
handleIncrement = (counter) => {
const countertemp = [...this.state.counters];
console.log("handle increment counter temp vlaue => ", counter)
const index = countertemp.indexOf(counter);
countertemp[index] = { ...counter };
countertemp[index].value++;
this.setState({ counters: countertemp });
};
const counters= [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 2 }, //2nd position
{ id: 4, value: 11 },
]
const counter={id: 3, value: 2}
const index = counters.indexOf(counter); //it doesnt return 2
console.log(index)
> -1
There is related answer here regarding indexOf but its confusing why it works in react and not in es6 repl
update:- another approach
React:-
handleIncrement = (counter) => {
const countertemp = [...this.state.counters];
//const index = countertemp.indexOf(counter);
const index = countertemp.map((x) => x.id).indexOf(counter.id)
countertemp[index] = { ...counter };
countertemp[index].value++;
this.setState({ counters: countertemp });
};
ES6:-
const counters= [
{ id: 1, value: 0 },
{ id: 2, value: 0 },
{ id: 3, value: 2 },
{ id: 4, value: 11 },
{ id: 11, value: 0 },
{ id: 23, value: 0 },
{ id: 43, value: 2 },
{ id: 453, value: 11 }, //7th
]
const counter={id: 453, value: 2}
const index = counters.map((x)=>x.id).indexOf(counter.id)
console.log(index)
> 7