Ad

Add Item To Array On ReactJs State With Timeout For Self Removal

- 1 answer

I have a created a MessageList component for displaying return messages from the server, I want these messages to only exist in the state for around 5 seconds or so, I have it all working as I want for adding and displaying, but I cant think for the life of me how to timeout the removal of a specific item from its parent array.. a Vanilla JS answer will do for timeout removal of self from array.

var MainApp = React.createClass({
     AddComment: function() {
        //do some stuff 
        this.showMessage({
            alerttype: "success", 
            title: "Success!", 
            message: "Comment saved to the database."})
        }
    },
    showMessage: function(message) {
        //how to I push this message onto messages for 5 seconds?
    },
    getInitialState: function() {
        return {messages: []};
    },
    render: function () {
        return (
            <div className="mainApp">
                <CommentForm messages={this.state.messages} />
            </div>
        );
    }
});
Ad

Answer

All you need to do is wrap the removal in a setTimeout. Something like the below:

showMessage: function(message) {
    this.setState({
        messages: this.state.messages.concat([message])
    });

    setTimeout(() => this.setState({
        messages: this.state.messages.filter(m => m !== message)
    }), 5000);
},
Ad
source: stackoverflow.com
Ad