DEV Community

choudhmh
choudhmh

Posted on

Unable to display data from Database

Hello;
I’m using React with axios and mysql. I’m trying to display data from the database. I’m managed to fetch the data and it shows the fetch data on my console.
But for some reason i’m finding it diffcult to show that fetched data on my webpage. I’ve looked around for issues but none seem to lead me to any help.

Image description

The Front end

const Display = () => {
  const [user, setUser] = useState([]);

  useEffect(() => {
    axios
      .get("http://localhost:8081/login")
      .then((res) => {
        console.log(res.data); // debugging
        // Set user to res.data.user if it's an array, else set to an empty array
        setUser(Array.isArray(res.data.user) ? res.data.user : []);
      })
      .catch((err) => console.log(err));
  }, []);


  const userDetails = user.map((item) => (
    <tr key={item.id}> 
      <td>{item.id}</td>
      <td>{item.name}</td>
      <td>{item.email}</td>
      <td>{item.password}</td>
    </tr>
  ));

  return (
    <div>
      Update
      <div>
        <table className="table"> 
          <thead>
            <tr>
              <th scope="col">#</th>
              <th scope="col">Name</th>
              <th scope="col">Email</th>
              <th scope="col">Password</th>
            </tr>
          </thead>
          <tbody>
            {userDetails}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default Display;
Enter fullscreen mode Exit fullscreen mode

The backend server code

app.get('/login', (req, res) =>{
    const sql = "SELECT * FROM login";
    db.query(sql, (err, data) => {
        if (err) {
            console.error(err);
            return res.json({ error: 'An error occurred' });
        }

        console.log(data);
        return res.json({ success: true, data: data });
    });
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)