Home > Enterprise >  ReactJS doesn't display content from array
ReactJS doesn't display content from array

Time:09-21

I fetch data from Firebase and then push that data to array with components. I am trying to display that by using the following code but React displays nothing, also there are no errors in console and during compiling.

import React, { useState ,useEffect } from "react";
import './App.css';
import db from "./firebase";
import { doc, getDocs, getDoc, collection, query, orderBy, limit, where } from "firebase/firestore";


function App() {

  useEffect(() => {
    getdata();
  }, []);

  const names = []

  async function getdata() {
    getDocs(collection(db,'questions')).then((snapshot) => {
      snapshot.forEach(doc => {
        names.push(<p className="question" >{doc.id}</p>)
        Object.values(doc.data()).forEach( test => {
          names.push(<p className="answer" >{test}</p>)
        });
      });
    })
  }

  return (
    <div className="App">
      {names}
    </div>
  )
}


export default App;

CodePudding user response:

You need to introduce state into your app.

Put your items into state, and then render JSX from your state

import { collection, getDocs } from 'firebase/firestore';
import React, { useEffect, useState } from 'react';
import './App.css';
import db from './firebase';

function App() {
  const [state, setState] = useState([]);

  async function getdata() {
    const snapshot = await getDocs(collection(db, 'questions'));

    const items = [];
    
    snapshot.forEach((doc) => {
      items.push({
        question: doc.id,
        answers: Object.values(doc.data()),
      });
    });

    setState(items);
  }

  useEffect(() => {
    getdata();
  }, []);

  return (
    <div className="App">
      {state.map((item) => (
        <React.Fragment key={item.question}>
          <p className="question">{item.question}</p>
          {item.answers.map((answer) => (
            <p className="answer" key={answer}>
              {answer}
            </p>
          ))}
        </React.Fragment>
      ))}
    </div>
  );
}

export default App;
  • Related