Hi guys , i'm trying to display the total number of staff that are in mongodb to my react app

Viewed 34
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function Count() {
  const [staff, setStaff] = useState([]);

  useEffect(() => {
    const fecthData = async () => {
      await axios.get('http://localhost:5000/api/users').then((res) => {
        setStaff(res.data);
        console.log(staff);
      });
    };
    fecthData();
  }, []);

  return (
    <div className='row'>
      <div className='col-md-8'>
        <ul className='list-group'>
          {staff.map((staff, index) => (
            <li key={index}>{index}</li>
          ))}
        </ul>
      </div>
    </div>
  );
}

export default Count;
1 Answers

Try to change your fetchData function to (you are mixing async await with then handling the Promise):

const fecthData = async () => {
      try {
        const { data } = await axios.get('http://localhost:5000/api/users');
        setStaff(data);
        console.log(staff);
      } catch (err) {
        console.log(err);
      }
    };
Related