IWI
IWI

Reputation: 1608

React updating a setState with a callback to a useState hook

I am updating the setStates I am using from class based components to functional ones. I have a few usecases where theres a closure. the code is

this.setState(

  ({ notifications }) => ({

    notifications: [...notifications, notification],

  }),

  () =>

    timeout !== undefined && window.setTimeout(closeNotification, timeout)

);

How do I use the useState hook to update this. I assume useState doesnt return a promise, so I cant use a .then. If thats the case, whats the best way to update this function?

Upvotes: 1

Views: 52

Answers (2)

Seth
Seth

Reputation: 10454

Maybe something like so?

const [notifications, setNotifications] = useState([]);

const doSomething = () => {
  setNotifications([ /* ... */ ]);
}

useEffect(() => {
  let timer;
  if(timeout !== undefined) {
    timer = setTimeout(closeNotification, timeout);
  }

  return () => clearTimeout(timer)
}, [notifications]);

Upvotes: 2

Hassan Azzam
Hassan Azzam

Reputation: 331

You can use the useState and the useEffect hooks to achieve the same result like so:

const [notifications, setNotifications] = useState([]);

useEffect(() => {

    // Close Notifications Here

}, [notifications]);

// To update the state use the setNotifications function like so
setNotifications(prevState => [...prevState, newNotification]);

the useEffect hook will run whenever you update the notifications.

Upvotes: 1

Related Questions