Home > front end >  undefined is not a function arr.filter
undefined is not a function arr.filter

Time:10-09

I am trying to filter data in flatlist but this error is showing up:

enter image description here

this is my code:

const [custData, setCustData] = useState([]);
  const [searchFilter, setSearchFilter] = useState('');

<FlatList
      data={custData.filter(item => {
        if (searchFilter === '') {
          return item;
        } else if (
          item.partyname
            .toString()
            .toLowerCase()
            .includes(searchFilter.toLowerCase())
        ) {
          return item;
        }
      })}
      keyExtractor={({id}, index) => id}
      renderItem={({item, index}) => (
        <Text style={{color: '#ffffff'}}>{item.partyname}</Text>
      )}
    />

CodePudding user response:

Instead of making changes in data of a FlatList, make a useEffect which will have custData as a parameter make changes to it and set the values to your state and render that state.

The code should look like this

const [custData, setCustData] = useState([]);
const [searchFilter, setSearchFilter] = useState('');

const toFilterData = async () => {
    return await custData?.filter(item => {
        if (searchFilter === '') {
          return item;
        } else if (
          item.partyname
            .toString()
            .toLowerCase()
            .includes(searchFilter.toLowerCase())
        ) {
          return item;
        }
      });
}

useEffect(() => {
    setSearchFilter(toFilterData());
}, [custData])

<FlatList
      data={searchFilter}
      keyExtractor={({id}, index) => id}
      renderItem={({item, index}) => (
        <Text style={{color: '#ffffff'}}>{item.partyname}</Text>
      )}
    />

Do try to use optional chaining will be helpful in future.

Thanks :)

  • Related