skip to Main Content

I am a beginner in MERN stack. I am just stuck at one place and it has been hours I cant solve it.

Issue:

When I press view users button in landing page, it takes me to view page where I want to render user lists. But it says No data available.
Error

CODE:

Landing Page:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import '../../src/App.css';
import { Button } from '@mui/material';
import { useNavigate } from 'react-router-dom';

const LandingPage = () => {
    const [alertShown, setAlertShown] = useState(false);

    useEffect(() => {
        if (!alertShown) {
            alert("You've successfully logged in!");
            setAlertShown(true);
        }
    }, [alertShown]);


    const navigate = useNavigate();

    const handleRedirectToView = () => {
        navigate('/view');
    };

    return (
        <div
            style={{
                backgroundImage: 'url("https://milonelawoffice.com/wp-content/uploads/2016/08/slide3.jpg")',
                width: 1280,
                height: 609,
                backgroundSize: 'cover',
                backgroundRepeat: 'no-repeat',
                paddingTop: 80
            }}
        >
            <headingText style={{ fontSize: "40px", textAlign: "center" }}>Welcome to the Dashboard!</headingText>
            <br></br>
            <center>
                <Button onClick={handleRedirectToView} variant="contained" sx={{ backgroundColor: '#C1C8EB', color: '#0C142C' }}>View Users</Button>
            </center>
        </div>
    );
};

export default LandingPage;

View page:

import React, { useState, useEffect } from 'react';
import '../../src/App.css';

const View = () => {
    const [data, setData] = useState([]);

    useEffect(() => {
      fetch("http://localhost:4000/getUser", {
        method: "GET",
      })
      .then((res) => res.json())
      .then((data) => {
        setData(data.data);
      });
    },[]);

    return(
        <div>
            {data && data.length > 0 ? (
                <table>
                    <thead>
                        <tr>
                            <th>Email</th>
                            <th>Password</th>
                        </tr>
                    </thead>
                    <tbody>
                        {data.map(i => (
                            <tr key={i.email}>
                                <td>{i.email}</td>
                                <td>{i.password}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            ) : (
                <p>No data available</p>
            )}
        </div>
    )

};

export default View;

I tried to get list of users.

I was expecting it to be rendered on screen.

But all I got was lists of users showing as array in JSON inside console of browser.

2

Answers


  1. Try to console data, i think that the state data is not set properly.

    useEffect(() => {
      fetch("http://localhost:4000/getUser") //there is no need for setting the method in this case because it's by default Get.
      .then((res) => res.json())
      .then((data) => {
        setData(data); //just the array of users
      });
    },[]);
    
    Login or Signup to reply.
  2. I can try to help you with one question and two tips:

    Q: Are you sure that data.data exists? setData(data.data); This should be the response structure if I’m not wrong:

    data: {
      data: {}
    }
    

    Maybe that’s what’s breaking your code.

    Tips:

    1. Use console.log(data) so you can check if data is being stored on state. (Should be before return() and after useEffect)
    2. Create a helper file with fetch method applying try catch.
      Here you’ll find some examples and more information about it.
      https://ilikekillnerds.com/2023/02/handling-errors-with-the-fetch-api/
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search