Reputation: 1
I am trying to output the data from axios get method but at the moment {event.title} is not giving any text eventhough the console.log shows that I recieved the data from the database. I am new to react native and have done plenty of reasearch but I can't seem to fix this problem. Any comment and idea would be very much appreciated!
const Events = () => {
const[event, getEvents] = useState('');
useEffect(() => {
getAllEvents();
}, []);
state = {
result: []
}
const getAllEvents = () => {
axios
.get(url)
.then((response) => {
const result = response.data;
getEvents({result});
console.log('Data has been recieved!');
console.log(result);
})
.catch(error => {
console.log('Error retrieving data!');
})
}
if(getEvents.length > 0) {
return(
<View>
<ScrollView>
<Text style = {styles.bigtext}>Eventet</Text>
<View nativeID = "allRows" style = {{flexDirection: "column",justifyContent: "center",alignItems: "center"}}>
<View nativeID = "row" style = {{flexDirection: "row",justifyContent: "center",alignItems: "center", margin: 1}}>
<View style = {styles.event}>
<TouchableOpacity onPress={() => { showModal(); }}>
<Image style = {{borderTopLeftRadius:10, borderTopRightRadius:10, height: 159, width: 159}} source={require('../../assets/45.png')} />
</TouchableOpacity>
{ result.map( event => <Text onPress={() => { showModal(); }} style = {styles.eventTitle}>{event.title}</Text>)}
</View>
</View>
</View>
</ScrollView>
</View>
);
}
else {
return(
<View>
<Text>No events!</Text>
</View>
);
}
};
Upvotes: 0
Views: 1184
Reputation: 1078
When you do "const result = response.data;" you are declaring a local variable which can not be reached outside of the ".then" function. But even if you declared it at a wider scope, it would still be set to null on the next render. You need to use useState (and use it correctly).
const Events = () => {
const[results, setResults] = useState([]);
const getAllEvents = () => {
axios
.get(url)
.then((response) => {
setResults(response.data ?? []);
})
.catch(error => {
console.log('Error retrieving data!');
})
}
And then
{results.map(event => <Text onPress={() => {showModal();}} style = {styles.eventTitle}>{event.title}</Text>)}
I am assuming here that the content of response.data is an array. If it isn't, you will not be able to use .map
Upvotes: 2