Restore transparent state onClick

I want to clear my state after onClick is fired. However, my state is not updated and instead displays 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
Run codeHide result

I have a button in another component that sets props on click, and my input field uses this as a value. When the value changes, the state is updated, which is working fine. However, when I then click the Refresh button, the data is updated correctly, but the status is not updated.

+4
source share
1 answer

Try putting setState in the then block. You can then call the block, and then never reach setState due to asynchrony.

Try putting setState in the following block as follows:

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

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

Source: https://habr.com/ru/post/1694644/


All Articles