I'm trying to render items from an array stored in state one at a time to the screen. After an item is displayed on the screen it is removed from the array, then the next item is displayed and so on until there are no items left in the array. The catch that has me sprung is that items can be added to the array via websockets while the function is already running. So essentially I want to create a live item queue. When an item or items are added to the queue, I want to the function to trigger and display the items on screen one by one until the queue is empty.
I thought using a recursive function that could initially be triggered by a useEffect might work. But what's weird is that inside my animateDisplay function the value for items never changes, but outside the function it changes like expected. It's like the value for items is cached within the recursive function. So my function repeats forever:
console.log(`outside ${items}`) // If items started as [1,2,3] it would log [1,2,3] then [2,3] then [3] on each render
const animateDisplay = async () => {
running.current = true
setDisplay(items[0])
await timeout(4000)
setDisplay({})
setItems(prevState => prevState.slice(1))
console.log(`inside ${items}`) // If items started as [1,2,3] it would log [1,2,3] on every render
if (items.length > 0) {
await timeout(4000)
await animateDisplay()
}
running.current = false
}
useEffect(() => {
if (running.current === false && items.length > 0) {
animateDisplay()
}
}, [items])
Is there anyway I can achieve what I am after?