Search code examples
typescriptreact-nativereact-native-flatlistsearchbarflatlist

Unable to assign data after search filter completes in react native typescript for custom object


I have a custom object an array and storing api response in it and showing that data into UI for flatlist.

export type userInfo = {
  id: string,
  title: string,
  email: string,
  userAccount: number
};

export type userData = {
  page: number,
  pageSize: number,
  userInformation: userInfo[]
}

export const User: FunctionComponent = () => {

       const [search, setSearch] = useState('');
      const [userInfo, setUserInfo] = useState<userInfo>();
  
      const [arrayholder, setArrayholder] =useState<userInfo>();

      useEffect(() => {
          setUserInfo(someState.userInfo);
          setArrayholder(someState.userInfo);
      }, [someState]);

searchData= (text: any)=>  {
            const newData = arrayholder?.userData.filter(item => {
                const itemData = item.title.toUpperCase();
                const textData = text.toUpperCase();
                return itemData.indexOf(textData) > -1
              });
              console.log("newData is", newData) //here throwing error
              setUserInfo(newData)
                setSearch(text)    
              }

}

          return (

//here showing searchbar
//here showing flatlist showing with userInfo

)

While trying to set newdata for userInfo, It is showing below error and unable to show search data in flatlist.

  Type 'userInfo[]' provides no match for the signature '(prevState: userInfo | undefined): userData | undefined'.ts(2345)

Any suggestions?

I am new to typescript language.


Solution

  • filter return an array:

    arrayholder?.activities.filter
    

    That‘s why userInfo requires an array type parameter.

    const [userInfo, setUserInfo] = useState<userInfo[]>();