Unable to clear the input field after submitting the form in React

Viewed 81
function Search() {
    let [state, setState] = useState({
        query: "",
        results: []
    })
let handleSubmit = e => {
        e.preventDefault();
        if(state.query.length>0) {
            fetch(searchURL)
            .then(response => response.json())
            .then(data => setState(prevValue => {
                return {
                    ...prevValue,
                        results: data.Search
                }
            })) 
setState({query:""})
        }

    }
    return (
        <div>
            <h1>Search</h1>
            <form onSubmit={handleSubmit}>
                <input type="text" placeholder="Search..." onChange={handleChange} value={state.query}/>
                <button type="submit">Search</button>
            </form>
        </div>
    )
}

After submitting the form, if I am setting the state, as in setState{query:""} , the API call is failing. How to acheive this. Thanks

5 Answers

Since the fetch API is asynchronous (your then chains will not immediately execute after fetch execution and it will wait until the fetch get resolved) you should add setState({query:""}) inside your last then promise chain.

So your code should be something like this:

.then(data => setState(prevValue => {
  return {
    ...prevValue,
    query: "",
    results: data.Search
  }
}))

There are two things you can do. In your second then, you can change the code there to be

.then(data => setState(prevValue => {
  return {
   ...prevValue,
    results: data.Search
    query: ''
   }
}))

You can omit the ...prevValue if you do not want to compute anything based on the previousState value

Or you can reset the form on success by calling e.target.reset()but since you are using the input as a controlled component. Go for the first alternative

I haven't used hooks too often, but I believe if you replace ...prevValue with query: ''. That should work?

setState(prevValue => {

            prevValue.query = "";

            prevValue.results= data.Search;   

            return {...prevValue};

});

}

Note : when you are updating any state , you can modify prevState variable just remember to return it as new deep cloned value for performance and correct practice.

Note: updating state is an async operation .

query has to be cleared after you receive the response like below:

{
      ...prevValue,
     results: data.Search,
     query: ""
}
Related