Search code examples
react-nativemobiledebouncing

Real Time search with API results using React Native


I'm following a tutorial to create my first React Native app. I'm using the search API from themoviedb.org and I want to refresh the results each time the user changes their input (instead of refreshing when they click a Search button.)

I'm using TextInput and onChangeText but if the user types too fast, there is a problem. I've found a possible solution is to use a "debounce" but I don't really know how to use it in my code.

Here is my code:

//Search.js

import React from 'react'
import { StyleSheet, View, TextInput, Button, FlatList, Text, ActivityIndicator } from 'react-native'

import FilmItem from './FilmItem'
import { getFilmsFromApiWithSearchedText} from '../API/TMDBApi'
import { debounce } from 'lodash'

class Search extends React.Component {

constructor(props){
  super(props)
  this.page = 0
  this.totalPages = 0
  this.state = { films: [], isLoading: false, searchedText:""}
}

_loadFilms(){
  if(this.state.searchedText.length > 0){
    this.setState({isLoading:true})
    console.log(this.state.films)
    getFilmsFromApiWithSearchedText(this.state.searchedText, this.page+1).then(data => {
      this.page = data.page
      this.totalPages = data.total_pages
      this.setState({ films: [...this.state.films, ...data.results]
        , isLoading:false})
    })
  }
}

_displayLoading(){
  if(this.state.isLoading){
    return (
      <View style={styles.loading_container}>
        <ActivityIndicator size='large' color='blue'/>
      </View>
    )
  }
}

_searchFilms(text){
    this.page = 0
    this.totalPages = 0
    this.setState({
      films:[], searchedText:text
    }, () => {
      this._loadFilms()
    })
}

_displayDetailForFilm = (idFilm) => {
  console.log("Display film with id " + idFilm)
  this.props.navigation.navigate("FilmDetail", {idFilm: idFilm})
}

/*_searchTextInputChanged(text){
  this.searchedText = text
}*/

render(){
  return (
    <View style={styles.main_container}>
      <TextInput style={styles.textinput}
      placeholder = 'titre du film'
      onChangeText={(text) => this._searchFilms(text)}
      />
      <Button title = 'Rechercher' /*onPress={()=>this._loadFilms()}*//>
      {this._displayLoading()}
      <FlatList
        data={this.state.films}
        keyExtractor={item => item.id.toString()}
        renderItem={({item}) => <FilmItem film={item} displayDetailForFilm={this._displayDetailForFilm} />}
        onEndReachedThreshold={0.5}
        onEndReached={() => {
          if(this.page < this.totalPages){
            this._loadFilms()
          }
        }}
      />
    </View>
  )
}

Solution

  • You can try with a timer to wait for user finished to type. Try something like

    constructor(props){
        super(props)
    
        this.searchTimer = null
    }
    
    setSearchTimer(text){
        clearTimeout(this.searchTimer)
        this.searchTimer = setTimeout(() => {
            this._searchFilms(text)
        }, 1000);
    }
    
    ...
    
    <TextInput style={styles.textinput}
        placeholder = 'titre du film'
        onChangeText={(text) => this.setSearchTimer(text)}
    />