Reputation: 159
I tried with the below code but it is executing on the second attempt, I want to execute Alert
on the Dropdown function, I am not rendering returnCount
just using it to display an alert,
anyone knows the answer plz answer this, don't send any link, nothing is working out instead please write the answer
const [arrayList, setArrayList] = useState([
{ Id: 1, Name:'A', ItemDeliveryStatus:4 },
{ Id: 2, Name:'B', ItemDeliveryStatus:4 },
{ Id: 3, Name:'C', ItemDeliveryStatus:4 },
{ Id: 4, Name:'D', ItemDeliveryStatus:4 },
])
const [returnCount ,setReturnCount ]=useState(0)
//function on the picker, want to update returnCount
immediately so that I can use it for below alert
function displayalertBox(){
arrayList.map(items =>
{
if(items.ItemDeliveryStatus=='4')
{
setReturnCount(prev=> prev+1)
}
})
if(returnCount==4)
{
alert('alert as returncount is equal to 4')
}
}
Upvotes: 1
Views: 1349
Reputation: 2053
You need to do the desired functionality inside of an useEffect
when using react hooks.
const [arrayList, setArrayList] = useState([{
Id: 1,
Name: 'A',
ItemDeliveryStatus: 4
},
{
Id: 2,
Name: 'B',
ItemDeliveryStatus: 4
},
{
Id: 3,
Name: 'C',
ItemDeliveryStatus: 4
},
{
Id: 4,
Name: 'D',
ItemDeliveryStatus: 4
},
])
const [returnCount, setReturnCount] = useState(0)
function displayalertBox() {
arrayList.map(items => {
if (items.ItemDeliveryStatus == '4') {
setReturnCount(prev => prev + 1)
}
})
}
// You cantry this too if needed.
function displayalertBox1() {
arrayList.map(items => {
if (items.ItemDeliveryStatus == '4') {
let count
setReturnCount(prev => {
count = prev + 1;
//since state update is guaranteed, you can try this too.
if (count === 4) {
alert('alert as returncount is equal to 4')
}
return count
})
}
})
}
useEffect(() => {
if (returnCount == 4) {
alert('alert as returncount is equal to 4')
}
}, [returnCount]);
Upvotes: 1