tomwassing
tomwassing

Reputation: 961

Why is setState returning undefined?

I am trying to close a modal when a user presses outside of the Modal element. Somehow when Dismiss() is called, the state is still the same in the callback.

Why is this happening?

export default class Message extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: "",
            show: false
        };
    }

    componentDidMount() {
        this.props.onRef(this);
    }

    Show(id) {
        this.setState({
            id: id,
            show: true
        });
    }

    Dismiss() {
        this.setState({
            id: '',
            show: false
        }, function (state) {
            console.log(state) // undefined
        });
    }

    render() {
        if (this.state.show) {
            return (
                <Modal close={() => this.Dismiss()}>
                    <h1>{this.state.id}</h1>
                </Modal>
            );
        } else {
            return null
        }
    }
}

Upvotes: 0

Views: 1728

Answers (2)

Xin
Xin

Reputation: 36590

Yes, that is because this.setState function in React is async. And the new state is only available in the event queue

Here is what I mean:

this.setState({newAdded: "test"});
let youCannotGetIt = this.state.newAdded; // here is undefined, because this.setSate is async

Upvotes: -2

Jayce444
Jayce444

Reputation: 9073

Not sure why there's a state argument in your callback, should just be

Dismiss() {
    this.setState({
        id: '',
        show: false
    }, function () {
        console.log(this.state)
    });
}

Upvotes: 6

Related Questions