I have been experimenting with fetching data from multiple API's using a Promise.all, and setting the data in state.
useEffect(() => {
Promise.all([
fetch("https://api.punkapi.com/v2/beers"),
fetch("https://api.sampleapis.com/beers/ale"),
fetch("https://api.sampleapis.com/beers/stouts"),
])
.then(([punkApi, ale, stouts]) => Promise.all([punkApi.json(), ale.json(), stouts.json()]))
.then(([punkApi, ale, stouts]) => {
setAllResults([...punkApi, ...ale, ...stouts]);
});
}, []);
Since each endpoint will have a collection of data, with each object having an ID, I have a large collection of elements that will share the same ID
https://api.sampleapis.com/beers/ale
[
{
"name": "Founders All Day IPA",
"id": 1
},
{
"name": "Blue Moon Belgian White Belgian-Style Wheat Ale",
"id": 2
}
]
https://api.sampleapis.com/beers/stouts
[
{
"name": "Founders CBS",
"id": 1
},
{
"name": "Founders KBS (Kentucky Breakfast Stout)",
"id": 2
}
]
My goal is the search by name and list the results. My initial thought is to combine the data into one array, filter by name, and return all that match.
If I search 'Founders', I get
[
{
"name": "Founders CBS",
"id": 1
},
{
"name": "Founders All Day IPA",
"id": 1
}
]
However when rendering lists in React Native, especially using key extractor, passing the ID as a key will now have two objects with the same key ID. I am unsure of how to approach this.
<FlatList
data={searched}
renderItem={({ item }) => <Result item={item} />}
keyExtractor={item => item.id = Math.random()}
/>
Setting the key extractor to making each object ID a random number works, but I feel like this is a bad practice, because each time the data is fetched, the ID will change.