My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

search filter not rendering flatlist react native

Raksha Hegde's photo
Raksha Hegde
·Apr 17, 2020

My flatList has 2 items displayed and if i search a text, it displays that item. But now when I start clicking backspace and delete my search text my other items are not displayed instead it’s still on the previous item.

My code below:

export default class HomeComponent extends Component {
  constructor(props){
    super(props)
      this.state = {
        isLoading: true,
        notifications: [],
        query: ''
      }
  };


  componentDidMount() {
    fetch('https://140xya6a67.execute-api.ap-southeast-1.amazonaws.com/dev/', {
    method: 'GET',
  })
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        notifications: responseJson,
        notificationRead: false
    })
    })
  };

  goToDetails() {
    return this.props.navigation.navigate(Details) ;
  }  


  renderItem({item}) {
    return <NotificationItem item={item} 
    onPress = {()=> {this.goToDetails()}}
    />
  }  


  handleSearch(text){
      const newData = _.filter(this.state.notifications, (item) => {
      const itemData = item.OrderDate ? item.OrderDate.toUpperCase() : ''.toUpperCase();
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1;
    });
    this.setState({
      notifications: newData,
      query:text,
    });
  }

  renderContent() {
    let {notifications} = this.state;

    return (
    <View>
    <SearchBar placeholder='type here...' lightTheme round value={this.state.query} onChangeText={(text)=>{this.handleSearch(text)}} />
    <FlatList
    keyExtractor={(item, id) => item.id} 
    data={notifications}
    renderItem={this.renderItem.bind(this)}
    /> 
    </View>

    );
  }


  render () {
  let {fill, container} = styles;

  return (
    <View style={ [fill, container] }>
      {this.renderContent()}
    </View>
  );
  }


}

The search filter works but as soon as i start clearing out the search text my flatlist is supposed to re-render to its initial state. Please check my code and let me know whats going wrong.