I am trying to create an image grid like the following on React Native.
I have managed to extract the data from https://pokeapi.co/ using Axios. My code is as the following so far but doesnt seem to work. The code below retrieves data from the API and I have set that data to setPokemon (How to I access this data) I have tried to assign that data to {data} below to be used inside the flatlist but its not working. It doesnt seem to assign the data at all.
export default function App() {
const [pokemons, setPokemon] = useState([])
//Fetching Pokemon from online database
async function fetchPokemon() {
try {
const { data } = await axios.get('https://pokeapi.co/api/v2/pokemon?limit=50')
setPokemon(data.results) // ASSIGN DATA TO setPokemon
}
}
//Hook to fetch Pokemon upon component mount
useEffect(() => {
fetchPokemon()
}, [])
const renderPokemon = (item, index) => {
return <Text>{item.name}</Text>
}
const {data} = setPokemon // ALL POKEMON SHOULD BE INSIDE THIS
return (
<SafeAreaView>
<FlatList
style={styles.container}
data={data} // ALL POKEMON SHOULD BE INSIDE THIS
renderItem={renderPokemon}
keyExtractor={pokemons => `key-${pokemons.name}`}
>
</FlatList>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
Any tips on this?
You are trying to access data from the state setter function. After calling setPokemon(5), pokemons will be 5.
const {data} = pokemons expects your data to be an object, but you've initialized it as a list, and it looks like you're trying to populate it as a list. Do you mean to write const data = pokemons to simply rename it rather than destructuring it?
Assuming that data.results is a list of stuff, here's what the working component will look like:
function App() {
const [pokemons, setPokemon] = useState([]);
async function fetchPokemon() {
try {
const { data } = await axios.get('https://pokeapi.co/api/v2/pokemon?limit=50')
setPokemon(data.results)
}
}
useEffect(fetchPokemon, [])
const renderPokemon = (item, index) => {
return <Text>{item.name}</Text>
};
return (
<SafeAreaView>
<FlatList
style={styles.container}
data={pokemons} // ALL POKEMON SHOULD BE INSIDE THIS
renderItem={renderPokemon}
keyExtractor={pokemons => `key-${pokemons.name}`}
>
</FlatList>
</SafeAreaView>
);
};
Edit: it seems like there is another error related to object destructuring. If you look at the FlatList docs the renderItem requires a function with this signature: (o: {item: T, index: number}) => Element. Simply update your renderPokemon function.