0
votes

I am new to using React with Firebase and I am struggling to return the data that I have in firebase. I have a collection called "users" and multiple documents inside with auto-generated IDs. I also have 3 fields in each document, fullname, email and id. This is the code I am using to fetch the documents:

function App() {

  const db = firebase.firestore();
  const [users, setUsers] = useState([])
  const fetchUsers = async () => {
    const response = db.collection('users');
    const data = await response.get();
    data.docs.forEach(item => {
      setUsers([...users, item.data()])
    })
  }

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

  return (
    <div>
      {
        users && users.map(user => {
          return (
            <div key={user.id}>
              <div>
                <h4>{user.fullname}</h4>
                <p>{user.email}</p>
              </div>
            </div>
          )
        })
      }
    </div>
  );
}

In the console, it is returning all of the documents in individual arrays but on the webpage, it is only returning the last document. Is there a way to return all of the documents? Any help would be appreciated, thank you.

1

1 Answers

1
votes

On your fetchUsers function you need to pass in a function with the previous state.

const fetchUsers = async () => {
const response = db.collection('users');
    const data = await response.get();
    data.docs.forEach(item => {
      setUsers((prevState)=>{return ({[...prevState, item.data()]})})
    })
  }