Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6213

Array types for useState

$
0
0

I have two cases in which I use setState to set an array of objects. Looks like this:

  const [friendList, setFriendList] = useState<any>();  const _onCompleted = (data: any) => {    let DATA = data.me.friends.map(      (item: {          firstName: string;          id: number;          rating: number;          vehicles: Array<Vehicle>;          friends: Array<User>;      }) => ({        id: item.id,        imageUrl: defaultUrl,        name: item.firstName,        rating: item.rating,        vehicles: [],        numberOfFriends: item.friends.length,      }),    );    setFriendList(DATA);  };

In case on onComplete, data looks like this:

DATAArray (3)0 {id: 1, imageUrl: "https://", name: "Bob", rating: 1, vehicles: [], …}1 {id: 3, imageUrl: "https://", name: "Rhena", rating: 3, vehicles: [], …}2 {id: 4, imageUrl: "https://", name: "Jack", rating: 4, vehicles: [], …}

Currently, I am using <any>, which works. However, I do not want to use any. I tried creating custom types:

type Friend = {  id: number,  imageUrl: string,  name: string,  rating?: number,  //vehicles: item.vehicles,  vehicles?: any,  numberOfFriends?: number,};type FriendList = {  friendList: Array<Friend>;};

but when I use it like this useState<FriendList>();, I get an error on setFriendList(DATA); from onError that Argument of type '{ id: string; imageUrl: string; name: string; }[]' is not assignable to parameter of type 'SetStateAction<FriendList | undefined>'.

Why is this so? The remaining fields in my Friend type are option so why do I get this error?

I also tried using useState<Array<Friend>>(); and useState([])but I get the same error.


Viewing all articles
Browse latest Browse all 6213

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>