Timer inside callback React

Viewed 28

I've a list of items I need to individually wait time for:

const products = [{
    itemID: 1,
    name: 2,
    remainingTime: 600
},
{
    itemID: 12,
    name: 333,
    remainingTime: 300,
}]

I'm trying to add popup is any of the product remaining time <= 100s doing something like this:

products.map((product) => {
    let remainingTime = product.remainingTime;
    useEffect(() => {
        if (remainingTime <= 100){
            addPopup("Time Expiring")
        }
    }, [remainingTime])
})

But react won't let me add useEffect inside the map. Is there a better way to accomplish this?

1 Answers

React updates all values if their parent are updated, so if products[1] are updated the whole map are "re-rendering" so you dont need to add a useEfect hook inside this .map, insted if you have a "countdown" living in each product you need to render a component and then use a useEffect inside this return so in mind i have this one

const ItemRenderer = ({ remainingTime }) => {
  useEffect(() => {
      // or if you wanna set a count down here are the site to
    if (remainingTime < 100) {
      // do your stuff if the prop change into this if
    }
  }, [remainingTime])
  return (
    <span>
      {remainingTime}
    </span>
  )
}


products.map(ItemRenderer)
Related