Search code examples
javascriptreactjsecmascript-next

Items being displayed when query is empty in react


I am learning react, and I have made a sample tv show app using an example off freecodecamp. It is all working okay from what I can see however after searching for something and then backspacing everything in the search box, it shows results when it shouldn't be, can anyone see a mistake I have made in my code?

class SeriesList extends React.Component {
  state = {
    series: [],
    query: ''
  }

  onChange = async e => {
    this.setState({query: e.target.value});
    const response = await fetch(
      `https://api.tvmaze.com/search/shows?q=${this.state.query}`
    );
    const data = await response.json();
    this.setState({series: data});
  }

  render(){
    return (
      <div>
        <input type="text" onChange={this.onChange} value={this.state.query} />
        <ul>
          <SeriesListItem list={this.state.series} />
        </ul>
      </div>
    );
  }
}

I have it on codepen here.

https://codepen.io/crash1989/pen/ERxPGO

thanks


Solution

  • One else point you can use await for setState

    onChange = async e => {    
        await this.setState({query: e.target.value});
        const response = await fetch(
          `https://api.tvmaze.com/search/shows?q=${this.state.query}`
        );
        const data = await response.json();
        this.setState({series: data});
      }
    

    Your request will be performed after changing query