can anyone please help me solve this problem, I am trying to get some attribute from the tempList state to store into listReceiver state by using gosetListReceiver()
function below.
const [tempList, setTempList] = useState([]);
const [listReceiver, setListReceiver] = useState([]);
function gosetListReceiver() {
let i = 0;
while (i < tempList.length) {
setListReceiver([
...listReceiver,
{
name: tempList[i]["name"],
phone: tempList[i]["receiver"]
}
]);
i++;
}
}
but when I am mapping/console the listReceiver
state after that , I expect that it will store 3 array from the tempList
into listReceiver
but it only have the last item from tempList
that stored into it. how can i fix this?
below the sample data of tempList
as i need to take name and receiver attribute to store into listReceiver
Every time through the loop, you are overwriting the state and thus wiping out anything you did on the last time through the loop. To fix this, you have two options.
setListReceiver((prev) => [
...prev,
{
name: tempList[i]["name"],
phone: tempList[i]["receiver"],
},
]);
function gosetListReceiver() {
let i = 0;
const newState = [...listReceiver];
while (i < tempList.length) {
newState.push({
name: tempList[i]["name"],
phone: tempList[i]["receiver"],
});
i++;
}
setListReceiver(newState);
}
P.S, this code looks like it would be better as a for
loop, instead of a while
loop:
const newState = [...listReceiver];
for (let i = 0; i < tempList.length; i++) {
newState.push({
name: tempList[i]["name"],
phone: tempList[i]["receiver"],
});
}
setListReceiver(newState);