0

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.

2
  • Where is the logic you have written to clear input field? Commented May 20, 2020 at 6:42
  • Added the comments in the code. Please check. Commented May 20, 2020 at 6:46

3 Answers 3

1

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: ''}}))

Sign up to request clarification or add additional context in comments.

1 Comment

Same thing is being done in the code provided by OP. Except for a few issues like destructuring.. 🤔
1

In your case, it could be done like this:

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

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.