Search code examples
reactjsreact-component

Where to use componentDidUpdate in React


I am a complete newbie in the world of development. I am trying to make an app where we fetch movies. We can search and sort. I don't want to use any plugins as of now.

I have been successful in fetching the data and showing on the grid. Also, searching is working well. But I'm confused if I shall put the searching method in componentDidUpdate React lifecycle hook or not. If it shall be how to do it?

Following is my code:

 class App extends Component
{
  constructor(props) 
  {
    super(props);
    this.state = {
    movies: [],
    filteredMovies: []
    }
  }

  componentDidMount()
  {
    axios.get('https://api.themoviedb.org/3/movie/top_rated?api_key={0}&language=en-US&page=1')
    .then(response => {
      this.setState({
        movies : response.data.results,
        filteredMovies : response.data.results
      });
    });
  }

  componentDidUpdate()
  {
    ???
  }

 searchBy = (columnSearch, evt) =>
  {
    console.log(columnSearch);
   let movie = this.state.movies;
   if (evt!==undefined && evt.target.value !== undefined && evt.target.value.length > 0) {
    movie = movie.filter(function(i) {
      console.log(columnSearch);
      return i[columnSearch].toString().match( evt.target.value );
    });
  }
  this.setState({
    filteredMovies: movie
  });
  }

  render(){
    const movieRows =( this.state.filteredMovies ===[] || this.state.filteredMovies === undefined)?[]:
    this.state.filteredMovies.map( (rowData, index) => <Movie key ={index} {...rowData} />);

         if(movieRows !== [] && movieRows !== undefined && movieRows !== null)
            return (
              <div className="table">
                <div className="header row">
                  <div className="headercenter">Movie Id
                  <input type="text"  onChange={(evt)=>this.searchBy('id',evt)}/>
                  </div>
                  <div className="headercenter"> Title <input type="text" onChange={(evt)=>this.searchBy('title',evt)}/></div>
                  {/* <div className="" onClick={() => this.sortBy('overview')}>OverView</div> */}
                  <div className="headercenter" >Popularity<input type="text" onChange={(evt)=>this.searchBy('popularity',evt)}/></div>
                  <div className="headercenter" >Rating<input type="text"  onChange={(evt)=>this.searchBy('vote_average',evt)}/></div>
                </div>
                <div className="body">
                  {movieRows}
                </div>
              </div>
            ) ;


     
  };
}
 


export default App;

    const movie = (props) => (
    <div className="row">
      <div>{props.id}</div>
      <div>{props.title}</div>
      {/* <div>{props.overview}</div> */}
      <div>{props.popularity}</div>    
      <div>{props.vote_average}</div>    
    </div>
  );

export default movie;

Solution

  • ComponentDidUpdate called when any state update take places inside the component, so you can put search method inside ComponentDidUpdate or any method but normally we do things inside ComponentDidUpdate which do require some state change and also do not require user input. For any searching you must be requiring user input so I don't recommend that you should put search method inside ComponentDidUpdate instead put that method on onChange event handler.

    Note: ComponentDidUpdate if not handled correctly i.e., you update any state inside this without any condition will cause Infinite Loop