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
Try to console
data
, i think that the statedata
is not set properly.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:Maybe that’s what’s breaking your code.
Tips:
Here you’ll find some examples and more information about it.
https://ilikekillnerds.com/2023/02/handling-errors-with-the-fetch-api/