shruti
shruti

Reputation: 117

How can i filter an state array in functional component in react native

enter image description hereI have an defined an array as state variable in a functional component

const [MessageResultsFirebase, setMessagesFirebase] = useState<MessageCellPropsFirebase[]>();

I want to filter it using Array.filter function to update the list.

var filterResult: MessageCellPropsFirebase = MessageResultsFirebase?.filter((element, index, array)=>{
       return (element.key == snapshot.key);
     });

but it gives the error "cannot find property filter of undefined". P.S: console.log(MessageResultsFirebase); works in same context.Please help i am new with these.

Upvotes: 1

Views: 396

Answers (1)

shruti
shruti

Reputation: 117

So it was happening due to the type declared in the Usestate function instead of

const [MessageResultsFirebase, setMessagesFirebase] = useState<MessageCellPropsFirebase[]>();

it should be

const [MessageResultsFirebase, setMessagesFirebase] = useState<Array<MessageCellPropsFirebase>>();

Hope it helps someone new Typescript.

Upvotes: 1

Related Questions