I face a problem in the array I get the data from firebase (firestore) and I want to show array of data how can i do?

Viewed 36
//data from Firebase 
[
  {
    "Role": "Student",
    "Section": "A",
    "StudentEmail": "amir@gmail.com",
    "StudentFather": "Atif Mian",
    "StudentID": "Bs-2000",
    "StudentName": "Amir Liaqat",
    "Subject": ["Web", "app"],
    "uid": "atwYEXNseKYyXfnTpldcTyL2Hj83"
  }
] 

I want to get only "Subject": ["Web", "app"] in the form of list

I used the code below but I think it was wrong

{subject
  ? subject.map((a, i) => {
      return <Text key={i}>{a}</Text>
    })
  : <></>
}

I received result "WebApp" but I need in the form of list.

I receive the data from there

const [subject, setSubject] = useState();

firestore()
  .collection('users')
  .where('uid', '==', StudentUID)
  .onSnapshot({
    error: e => console.error(e),
    next: querySnapshot => {
      var data = [];
      var sub = [];
      querySnapshot.forEach(doc => {
        data.push(doc.data());
        sub.push(doc.data().Subject);
      });
      setStudents(data);
      setSubject(sub)
      console.log(sub)
    },
  });
1 Answers

Assuming the subject state is the array of Subject properties, also an array, from the data containing objects like the following:

[
  {
    "Role": "Student",
    "Section": "A",
    "StudentEmail": "amir@gmail.com",
    "StudentFather": "Atif Mian",
    "StudentID": "Bs-2000",
    "StudentName": "Amir Liaqat",
    "Subject": ["Web", "app"],
    "uid": "atwYEXNseKYyXfnTpldcTyL2Hj83"
  },
]

Then this means the subject state is an array of arrays, i.e. [["Web", "app"], ...]. ["Web", "app"] is valid JSX and will pretty much be rendered directly as is, one string value then the other, with no separator characters, e.g. "Webapp".

The simplest solution would be to join this array and convert it to a string when mapping, specifying the separator character you'd like, i.e. "Web, app".

Example:

const [subjects, setSubjects] = useState([]); // <-- valid initial state

...

firestore()
  .collection('users')
  .where('uid', '==', StudentUID)
  .onSnapshot({
    error: e => console.error(e),
    next: querySnapshot => {
      var data = [];
      var sub = [];
      querySnapshot.forEach(doc => {
        data.push(doc.data());
        sub.push(doc.data().Subject);
      });
      setStudents(data);
      setSubjects(sub);
    },
  });

...

{subjects.map((subject, i) => (
  <Text key={i}>{subject.join(", ")}</Text> // `["Web", "app"]` => "Web, app"
)}

There is no need really to duplicate this subject state, you can easily map it from the students state.

{students.map(({ StudentID, Subject }) => (
  <Text key={StudentID}>{Subject.join(", ")}</Text> // "Web, app"
)}
Related