简体   繁体   中英

React input field not emptying after submission

I am trying to write a react code to submit the value to the backend server. I want the input field to be cleared out as soon as the user hits submit button.

I have written the below code, could anyone help me with what I am missing here?

class Create extends Component {

    state = {
        task : {
            title: '',
            completed: false
        }
    }
    CreateHandler = (event) => {
        this.setState((state) => {
            return {
                task: {
                    ...state, title: '' // <----- CLEARING HERE (well, trying)
                }
            }
        });
        event.target.value=""; // <----- ALSO HERE 
        event.preventDefault();
        axios({
            method:'post',
            url:'http://localhost:8000/api/task-create',
            data: this.state.task,
            xsrfHeaderName: this.props.CSRFToken
        })
        .then((res) => {
            console.log(res.data);
        })
        this.props.updateState(this.state.task)
    }
    ChangeHandler = (event) => {
        this.setState(state => {
            return {
                task: {
                    ...state, title: event.target.value
                }
            }    
        })
     }

Breaking the code in parts so that it's easily readable.

    render() {
        return (
            <form onSubmit={this.CreateHandler.bind(this)}>
                <div className="header form-group">  
                    <input 
                    className="newItem form-control"
                    onChange={this.ChangeHandler.bind(this)}
                    value={this.state.task.title}
                    />
                    <button 
                        type="submit" 
                        class="saveButton btn btn-primary btn-warning">
                            submit
                    </button>
                </div>
            </form>
        )
    }
}

export default Create;

The end goal is to clear the input field and then send the data to the backend django server, which is being done successfully except the input field being cleared.

You are not updating state correctly

this.setState((state) => {
            return {
                task: {
                    ...state, title: '' // <----- CLEARING HERE (well, trying)
                }
            }
        });

should be

this.setState((state) =>({...state, task: {...state.task, title: ''}}))

In your case, it could be done like this:

this.setState(previousState => ({
    task: {
        ...previousState.task,
        title: '' // <----- CLEARING HERE
    }
}));

A better way to write your createHandler method:

CreateHandler = (event) => {
  // Prevent the default form action
  event.preventDefault();

  // Call your API
  axios({
    method: "post",
    url: "http://localhost:8000/api/task-create",
    data: this.state.task,
    xsrfHeaderName: this.props.CSRFToken,
  }).then((res) => {

    // Request passed
    // Call your prop function
    this.props.updateState(this.state.task);

    // Clear the unnecessary data
    this.setState((prevState) => ({

      // Create new object
      task: {

        // Assign the properties of previous task object
        ...prevState.task,

        // Clear the title field
        title: "",
      },
    }));
  });
};

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM