ReactJs: Unable to loop over array of object using map

Viewed 688

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": "t@j.com"},{"fullname": "Femi", "mail": "ht@h.com"}]

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;
3 Answers

You are returning an object from your map function. You need to add a return or simply use the short arrow syntax like so:

<Text>Attendance screen</Text>
         {
           this.state.getCourse.map((y) => <Text>{y.fullname</Text>)
         } // notice the lack of {}, if you dont like this syntax just add a return before <Text ;

Also after you fix this React will complain about missing keys so either add an index value (not usually recommended if the array can change) or use some unique value from your datasource.

You always save a string to async storage so do a JSON.parse

 await AsyncStorage.getItem('course').then(value =>
        //AsyncStorage returns a promise so adding a callback to get the value
        this.setState({ getCourse: JSON.parse(value) })
        //Setting the value in Text 
      );

According to your current code you try to call the map function on a string which is causing the error and you wont see the quotes when displaying that.

render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> 
        <Text>Attendance screen</Text>
         {
           this.state.getCourse.map((y) => {
            return (<Text>{y.fullname}</Text>)
           })
         } // This will not work
        <Text>{JSON.stringify(this.state.getCourse)}</Text>// This will display the array in a json format
      </View>
    );

}

AsyncStorage.getItem('course') is returning an object and you can't loop over that, but instead you can just directly access fullname,course,email and use them in ur UI .

async componentDidMount(){
    try {
      await AsyncStorage.getItem('course').then(value =>
          const course = JSON.parse(value)
          if(course ) this.setState({ getCourse: course } )
      );
      } catch (e) {
      alert(e);
    }
  }

  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> 
        <Text>{this.state.getCourse.fullname }</Text>
        <Text>{this.state.getCourse.mail}</Text>
        <Text>{this.state.getCourse.course}</Text>

      </View>
    );
  }
Related