1 year ago

#384056

test-img

guergana

Creating an individual setTimeout for each rendered element in a map in React

I am creating an app where there is a list of elements created from an array of objects, and i am rendering them in a map like this

<div className="App">
      <div className="notification-list">
        {
          notifications.map( (({ type, text }, i ) => {
            return (
            <Notification
              handleClick={handleCloseNotification}
              key={i}
              index={i}
              type={type}
              text={text} 
            />
          )} ))
        }
      </div>

each notification should disappear after X seconds after being rendered... I have tried several approaches for adding the setTimeout but none of them has worked so far.

I tried

useEffect(() => {
    const timer = setTimeout(() => 
      notifications.map(({}, index) => (
        handleCloseNotification( index )
      )), 10000);
    return () => clearTimeout(timer);
  }, [notifications]);

I also tried adding this

const timer = setInterval(() => handleClick( index ), 1000);

inside the Notification component.

I also tried this

<div className="notification-list">
        {
          notifications.map( (({ type, text }, i ) => {
            const timer = setTimeout(() => {
              handleCloseNotification( i)
              console.log(i);
            }, 10000);
            return (
            <Notification
              handleClick={handleCloseNotification}
              key={i}
              index={i}
              type={type}
              text={text} 
            />
          )} ))
        }
      </div>

Since I have a list that initially renders several Notifications at the same time my expectation is that they all disappear at the same time. Yet the elements disappear one by one with an interval of 10 seconds between them.

There is a form that adds new notifications to the form, and those Notifications should each live for 10 seconds and then disappear. This part seems to be working but for the elements that are rendered initially why aren't they working as I expect?

Thanks.

javascript

reactjs

react-hooks

dynamic-arrays

0 Answers

Your Answer

Accepted video resources