Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use React's getDerivedStateFromProps with a setTimeout?

I want to create a Modal-like component that receives an open/closed boolean as a prop, then stores that value in the component state. When closing the Modal, I want to update the close boolean prop, but wait a few seconds before updating the component state so that I can add transition classes and animate the exit.

With componentWillReceiveProps, I could accomplish this by wrapping this.setState in a timeout and add the classes in the meantime. With the new React 16.3 API, I see that is is recommended to use the getDerivedStateFromProps instead.

Since getDerivedStateFromProps "should return an object to update state, or null to indicate that the new props do not require any state updates," (React docs) I want the method to look something like this:

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.menuIsOpen === false && prevState.menuIsOpen === true) {
        return setTimeout(() => { menuIsOpen: false}, 1000);
    }
    return null;
}

But that doesn't work. I've read that setTimeout does not return a value but am wondering if there is a more elegant solution to the problem than returning a promise.

like image 528
SeanMcP Avatar asked Dec 23 '22 07:12

SeanMcP


1 Answers

You can use componentDidUpdate:

componentDidUpdate(prevProps){
    // update your class names...
    if (!this.props.menuIsOpen && this.state.menuIsOpen) {
        setTimeout(() => this.setState({ menuIsOpen: false}), 1000);
    }
}
like image 135
Tomasz Mularczyk Avatar answered Dec 25 '22 21:12

Tomasz Mularczyk