0

I am making a todo app in react and after taking input from the user on submit i am making a post request to update in the database and then updating the state. and then i am trying to clear the input field using e.target.value = "". But this is not working. Iam fairly new to JS and React. can some one point me what i am doing wrong here.

class TodoApp extends Component {
    constructor(props) {
        super(props);

        this.state = {
            todos: [],
        };`enter code here

        this.handleTodos = this.handleTodos.bind(this);
        this.handleLogout = this.handleLogout.bind(this);
        this.removeTodo = this.removeTodo.bind(this);
    };

    componentDidMount() {

        const authStr = 'Bearer ' + getJWTToken();

        axios.get('/tasks', {
            'headers': {
                'Authorization': authStr
            }
        }).then(res => {
            // console.log(res.data);
            this.setState({
                todos: res.data,
            })
        }).catch(err => {
            console.log(err);
        });

    };

    removeTodo = id => {
        //  console.log(id)

        const authStr = 'Bearer ' + getJWTToken();

        axios.delete('/tasks/' + id, {
            'headers': {
                'Authorization': authStr
            }
        }).then(res => {
            // console.log(res.data);
            let newTodos = [...this.state.todos];

            newTodos = newTodos.filter(todo => {
                return todo._id !== id;
            });

            //Update the State
            this.setState({
                todos: newTodos
            });
        }).catch(err => {
            console.log(err);
        });

    };

    handleTodos = e => {

        e.preventDefault();
        const authStr = 'Bearer ' + getJWTToken();

        var todo = {
            description: e.target.value
        }

        console.log(todo)

        axios.post('/tasks', todo, {
            'headers': {
                'Authorization': authStr
            }
        }).then(res => {
            // console.log(res.data);
            this.setState({
                todos: this.state.todos.concat(res.data)
            })
        }).catch(err => {
            console.log(err)
        });

        e.target.value = "";
        // console.log(todo);
    };

    handleLogout() {
        localStorage.removeItem('jwtToken');
        this.props.history.push("/");
    }

    render() {

        const listLayout = {
            labelCol: {
              xs: { span: 24 },
              sm: { span: 8 },
            },
            wrapperCol: {
              xs: { span: 24 },
              sm: { span: 16 },
            },
          };      

        return (
            <div className="container-fluid App">
                <div className="todoContainer">
                    <Header
                        handleLogout={this.handleLogout}
                    />

                    <h1 style={{ paddingTop: "10px" }}>TODO App</h1>

                    <Input
                        placeholder="What needs to be done?"
                        onPressEnter={this.handleTodos}
                    />

                    <List
                        itemLayout="horizontal"
                        locale={{ emptyText: "No Todos" }}
                        dataSource={this.state.todos}
                        renderItem={item => (
                            <TodoItem
                                todo={item}
                                removeTodo={this.removeTodo}
                            />
                        )}
                    />

                </div>
            </div>
        );
    };

};

export default TodoApp;
  • You can clear the field value by setting the state to that input field or you can use ref for input. – karthik Apr 22 '19 at 09:06

4 Answers4

0

The value of your input field should be bound to your state to properly control it. You can modify your state declaration like this:

this.state = {
    todos: [],
    whatToDo: ""
}

and bind your input field to your state like this:

<Input
    placeholder="What needs to be done?"
    onPressEnter={this.handleTodos}
    value={this.state.whatToDo}
    onChange={this.onInputChange} // will update the state on each change
/>

then create the onInputChange function:

onInputChange= (event, data) => {
    this.setState({ whatToDo: data.value });
}

and lastly, change the line

e.target.value = "";

to

this.setState({ whatToDo: "" });
0

try this,

  handleTodos = e => {

        e.preventDefault();
        const authStr = 'Bearer ' + getJWTToken();

        var todo = {
            description: e.target.value
        }

        console.log(todo)

        axios.post('/tasks', todo, {
            'headers': {
                'Authorization': authStr
            }
        }).then(res => {
            // console.log(res.data);
            this.setState({
                todos: this.state.todos.concat(res.data)
            })
        }).catch(err => {
            console.log(err)
        });
        //RESET FIELD
        e.target.reset()
    };
sathish kumar
  • 1,477
  • 1
  • 11
  • 18
0

You can use Refs to clear input text. This is the working solution.Also, follow this Reactjs link for more information.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      inputField: ""
    };
  }
  keyHandler = event => {
    if (event.key === "Enter") {
      console.log(this.inputRef.current.value);
      this.setState({ inputField: event.target.value });
      this.inputRef.current.value = "";
    }
  };
  render() {
    return (
      <div>
        <input
          type="text"
          onKeyPress={this.keyHandler}
          ref={this.inputRef}
        />
        <p>{this.state.inputField}</p>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>
Engineer
  • 1,243
  • 11
  • 18
0

Allow me to tell you that this is not the react way of working generally speaking with inputs. I could also try to fix your error, but I prefer to bring you on the right path. Have a look at this doc page: https://reactjs.org/docs/forms.html

Particularly this stackoverflow answer: What are controlled components and uncontrolled components in ReactJS?

Using controlled components, to clear the input field, you just call setState emptying the content of a particular state variable. Please, have a look at the example I'm about to write:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
  }

  handleChange = (event) => {
    this.setState({value: event.target.value});
  }

  handleSubmit = (event) => {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  emptyInput = () => {
    alert('Emptying input');
    this.setState({ value: '' });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
        <button onClick={emptyInput}>Empty input</button>
      </form>
    );
  }
}
Giacomo Cerquone
  • 2,352
  • 5
  • 24
  • 33