MartinDK81
MartinDK81

Reputation: 343

React clear state onClick

I want to clear my state after onClick has been fired. However, my state doesn't update, and instead renders the initial state.

Here is the code

import React from 'react';
import {firebaseCon} from '../connection';

class Update extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
			title: ""
        };

        this.updateItem = this.updateItem.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }

    componentWillReceiveProps(props) {
        this.setState({
            title: props.item.title
        });
    }

    updateItem(itemId) {
        let inputVal = document.getElementById("editData").value;
        firebaseCon.content.update('text', itemId, { title: inputVal })
        .then(() => console.log('Updating the entry succeeded'))
        .catch((e) => console.error(e));
        this.setState({ title: "" });
    }

    handleChange(e) {
        var value = e.target.value;
        this.setState({ title: value });
    }

    render() {
        return (
            <div className="input-field col s12">
                <i className="material-icons prefix">mode_edit</i>
                <input type="text" id="editData" value={this.state.title || ""} onChange={this.handleChange} />
                <button className="waves-effect waves-light btn" onClick={this.updateItem.bind(this, this.props.item.id)}>UPDATE</button>
            </div>
        )
    }
}

export default Update

I have a button in another component, that sets the props when clicked and my inputfield then use this as value. When changing the value, the state updates, which is working fine. However, when I then click my update button, the data is correctly updated, but the state is not updated.

Upvotes: 4

Views: 11496

Answers (1)

Dream_Cap
Dream_Cap

Reputation: 2302

Try putting setState in the then block. The then block could be getting called and then never reaching setState because of asynchrony.

Try putting setState in the then block like this:

then(() => {
  console.log('Updating the entry succeeded');
  this.setState({title: ""}); // <--- goes inside the then block, so it gets executed 

}).catch((e) => console.error(e));

Upvotes: 1

Related Questions