Search code examples
javascriptnode.jsapisearchbarflatlist

Implementing searchbar into flatlist to search api data react native


I've implemented an searchbar as a header of a flatlist which displays my api data (the flatlist works fine ) but the searchbar don't work , i've tried several codes but stills not working If someone can help me with this i'll appreciate it :)

My API displays an document which contains : -Titre(String) -Montant(Number) I want to search by Titre . Here's the last code that i've tried :

   class listDépenses extends React.Component{ 
   constructor() {
   super();
   this.state = {
   refreshing: true,
   dataSource: [],
   Montant:'',
   Titre:'',
   modalVisible:false,

   loading: false,      
   data: [],      
   error: null, 
   }
   this.arrayholder = [];
   }

   renderItem = ({item}) => {

   <View style={{flex:1}}>
   <Text style={[globalStyles.sousTitre,{marginVertical:10,marginLeft:10}]}>{item.Titre}</Text>
   <Text style={[globalStyles.sousTitre, 
        {marginVertical:10,marginLeft:40,textAlignVertical:'auto',opacity:0.8,fontWeight:'800'}]}> 
   {item.Montant}</Text>
    </View>}

    searchFilterFunction = text => {    
     const newData = this.arrayholder.filter(item => {      
    const itemData = `${item.Titre.toUpperCase()}`;
    const textData = text.toUpperCase();
    return itemData.indexOf(textData) > -1;    
    });


    renderHeader = () => { 
   return(   
    <SearchBar
    placeholder="Tapez ici..."
    onChangeText={text => this.searchFilterFunction(text)}
    round="default"
    lightTheme="default"
   />
   ) 
   }
  this.setState({ data: newData });  
   };
 
  async componentDidMount() {
   await fetch ('http://192.168.1.10:8080/api/depenses',{
   method:'get',
   mode:'no-cors',
   headers:{
  'Accept':'application/json',
  'Content-Type':'application/json'
   }})
   .then((response) => response.json())
   .then((responseJson) => {
   this.setState({
    dataSource:responseJson,
   data: responseJson.results,          
   loading: false,   
   })
  this.arrayholder = responseJson.results;      

 })
.catch((error) =>{
 console.log(error) 
})}
   
    render(){
    return (

    <View style={{flex:1}}>


  <View style={{marginBottom:10}}></View>
  
   <FlatList
        data={this.state.dataSource}
        renderItem={this.renderItem}
        keyExtractor={(item, index) => index}
        ItemSeparatorComponent={this.renderSeparator}
        ListHeaderComponent={this.renderHeader}                             
      />

    </View>

Solution

  • I've found the solution if anyone need it :

         class listDépenses extends React.Component{
         constructor(props) {
         super(props);
        this.delayValue = 8000;
    
        this.state = {
         search:'', 
         dataSource: [],
         animatedValue: new Animated.Value(0),
         Montant:'',
         Titre:'',
         isLoading:true,
         modalVisible:false,
         }
          this.arrayholder=[]
          }
    
          componentDidMount() {
           Animated.spring(this.state.animatedValue, {
          toValue: 1,
         tension: 20,
         useNativeDriver: true
         }).start();
        return fetch('http://localhost:8080/api/depenses')
       .then((response )=> response.json())
        .then(responseJson => {
       this.setState({
       dataSource: responseJson,
       isLoading: false,
       },
      function() {
      this.arrayholder = responseJson;
       });})
    .catch(error => { console.error(error);});}
      search = text => { console.log(text);
      };
     clear = () => { this.search.clear();
     };
     SearchFilterFunction(text) {
      const newData = this.arrayholder.filter(function(item) { const itemData = item.Titre 
      ? item.Titre.toUpperCase() :
      ''.toUpperCase();
      const textData = text.toUpperCase(); return itemData.indexOf(textData) > -1;
      });
      this.setState({ dataSource: newData, search: text,
      });
      }
    
    
     render(){
    
     if (this.state.isLoading) { return (
      <View style={{ flex: 1, paddingTop: 21 }}>
      <ActivityIndicator />
      </View>
      );
      }
        return (
    
        <View style={styles.container}>
        <SearchBar 
         round="default"
         lightTheme="default"
         searchIcon={{ size: 25 }}
         onChangeText={text => this.SearchFilterFunction(text)} onClear={text => 
         this.SearchFilterFunction('')} placeholder="Tapez ici pour chercher..." value= 
         {this.state.search}
         />
        <View style={{marginBottom:10}}></View>
      
        <FlatList
        data={this.state.dataSource}
        renderItem={this.renderItem}
        keyExtractor={(item, index) => index.toString()}
        enableEmptySections={true} style={{ marginTop: 11 }}
        ItemSeparatorComponent={this.renderSeparator}
          />
        </View>