简体   繁体   中英

How to do searching in react native?

I'm trying to implement a dictionary in my app.For that I'm fetching an api response which contains the data for dictionary. The api response will be based on the input given by user.If I type letter a then corresponding result will be produced.But on further typing of full word ,say adhaar then what I'm expecting is to render only that purtcular item.But in my case whatever I type in the search field the result will be same even after the full word is typed.Also I'm not getting the result of word which I'm typing. I'm following this doc Please help me to figure out my mistake.What wrong I'm doing?Please help.Following is my code

  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      data:[]
    };
    this.arrayholder = [];
  }
searchFilterFunction = text =>{
  this.setState({ text });
  console.log(this.state.text);
    fetch('xxxxxx', {
         method:'POST',
         headers: {
             'Accept': 'application/json'
         },
         body:JSON.stringify({
           s:text,
           loading:false
         })
     }).then((response) => response.json())
     .then((responseData) => {

          this.setState({
              data:responseData.data
          })

          this.arrayholder = responseData.data

     })
     .catch(error => {
     this.setState({ error, loading: false });
   });
   const newData = this.arrayholder.filter(item => {
    const itemData = `${item.post_title}`;
     const textData = text;
     return itemData.indexOf(textData) > -1;
     this.setState({ data: newData });
  });

   }
<Container>
     <Header>
         <Item>
           <Input placeholder="Search"
           onChangeText={text => this.searchFilterFunction({text})}
           />
         </Item>
       </Header>
    ...
     ...
   <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
       <FlatList
       data={this.state.data}
       renderItem={({ item }) => (
       <Text>{item.post_title}</Text>
       )}
       keyExtractor={(item, index) => index.toString()}
       ItemSeparatorComponent={this.renderSeparator}
       />
       </List>
  <Container>

This is how the output screen will be https://i.stack.imgur.com/gXhTb.png

Any help is appreciated.Thank you!

This is due to a scope issue. You have code executing in an asynchronous and code executing after this depending on the asynchronous result. This isn't going to work for you.

There are a few issues in the searchFilter function.

When you are creating the newData the setState is written in the filter after the return statement. It will never get called so you are never updating your state.

You're also, what seems to be unnecessary, calling setState multiple times. I think you only need to call it twice. Once when the data has been downloaded and once when the data fails to download.

Here is an updated searchFilterFunction , this should give you some ideas on how you could fix your code.

searchFilterFunction = text =>{
  console.log(text);
    fetch(
      ...
    )
    .then((response) => response.json())
    .then((responseData) => {

      const filteredData = responseData.data.filter(item => {
        const itemData = `${item.post_title}`;
        const textData = text;
        return itemData.indexOf(textData) > -1;
      });

      this.setState({
          data: filteredData, 
          text
      });
    })
     .catch(error => {
     this.setState({ error, loading: false, text });
   });
}
  • I have removed the setState for text at the start, are you needing to set it here as it will force a re-render.

  • In the .then((responseData) => ... ) I have updated it so that you perform the filter straight away on the responseData.data , then save the filteredData and the text to state.

  • I removed the setting of this.arrayholder I don't think you really require it unless you are using it elsewhere.

In your FlatList I would add the extraData prop

A marker property for telling the list to re-render (since it implements PureComponent)

<FlatList
  ...
  extraData={this.state}
  ...
>

Hopefully that should be enough for your to fix your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM