While trying to loop over an array of object retrieved from the database in ReactJs, I always get this error
this.state.getCourse.map is not a function. (In 'this.state.getCourse.map(function (y) {
(Device)
_react.default.createElement(_reactNative.Text, null, y.fullname);
})', 'this.state.getCourse.map' is undefined)
I don't know why I always get this error as if I simply use
<Text>{this.state.getCourse}</Text>
it will display the saved objects in an array objects format like this
[{"fullname": "Gbenga", "mail": "[email protected]"},{"fullname": "Femi", "mail": "[email protected]"}]
but if I looped through it, it always returned the above error.
This is what I have done so far.
// screens/Attendance.js
import React, { Component } from 'react';
import { Button, View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
class Attendace extends Component {
constructor() {
super();
this.state = {
getCourse: [],
};
}
async componentDidMount(){
try {
await AsyncStorage.getItem('course').then(value =>
//AsyncStorage returns a promise so adding a callback to get the value
this.setState({ getCourse: value })
//Setting the value in Text
);
} catch (e) {
alert(e);
}
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Attendance screen</Text>
{
this.state.getCourse.map((y) => {
<Text>{y.fullname}</Text>
})
} // This will not work
<Text>{this.state.getCourse}</Text>// This will display the array in a json format
</View>
);
}
}
export default Attendace;
console.info(typeof this.state.getCourse )render() { console.info(typeof this.state.getCourse ) return (AsyncStorage.getItemreturns a string in promise. Trythis.setState({ getCourse: JSON.parse(value) })