I am passing data from my backend to frontend using axios but it is executing two times and is showing undefined for the first time but everything works fine on the second time.(I am console logging it to check the values).My question is that why is it executing two times. This is the front end part below and my axios request is inside useEffect
import React, { useState, useEffect } from 'react';
import './JournalPage.css';
import {useParams} from "react-router-dom";
import axios from "../axios.js";
import Logo from './Logo';
// import MenuBookIcon from '@mui/icons-material/MenuBook';
// import ViewWeekIcon from '@mui/icons-material/ViewWeek';
// import ListAltIcon from '@mui/icons-material/ListAlt';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import Navbar from './Navbar';
import Blog from './Blog';
function JournalPage() {
let {username} = useParams();
const [userData, setuserData] = useState("[]");
useEffect(() =>{
async function fetchData() {
const req = await axios.post("/userdata",{username});
setuserData(req.data);
}
fetchData();
}, []);
console.log(username);
console.log(userData);
// const monthNames = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"];
// const dayNames = ["Sunday","Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
// const dateObj = new Date();
// const month = monthNames[dateObj.getMonth()];
// const day = String(dateObj.getDate()).padStart(2, '0');
// const weekday = dayNames[dateObj.getDay()];
// const year = dateObj.getFullYear();
// const output = month + '\n'+ day + '\n' + year + ',' + weekday;
return (
<div className="journal">
{/* <header className="header">
<h1>🅽<span>ð</span>т𝒮ᴄг<span>🅰</span>𝓹</h1>
</header> */}
<header className="header">
<Logo />
{/* <h3>{output}</h3> */}
<h3><AccountCircleIcon className="icon2" fontSize="large"/>{userData.name}</h3>
</header>
<div className="navcon">
{/* <div className="navbardiv">
<ul>
<li><MenuBookIcon className="icon1"/>My Journal</li>
<li><ViewWeekIcon className="icon1"/>Week Planner</li>
<li><ListAltIcon className="icon1"/>Daily To Do's</li>
</ul>
</div> */}
<Navbar id={userData._id}/>
<div className="content">
<Blog blog={userData.blog}/>
</div>
</div>
</div>
)
}
export default JournalPage
app.post("/userdata", (req, res) =>{
console.log(req.body);
const id=req.body.username;
User.findOne({_id: id}, function(err, foundUser){
if(err){
console.log(err)
} else{
console.log(foundUser);
res.send(foundUser);
}
});
});
This is what I am getting in my console. Line 4 to 7 is getting repeated. I am not getting anything back on the first go but everything works fine in the second go. This is the console ss.
This is blog component
import React from 'react';
import "./Blog.css";
function Blog({blog}) {
console.log(blog);
return <div className="blog">
<h1>{blog[0]?.date}</h1>
<p>{blog[0]?.post}</p>
</div>;
}
export default Blog;
If it's when you console.log
userData
, then this is expected behaviour as you are logging it outside of the effect. This is because on first render, an effect is called last in the life cycle of a component, so the value will be undefined.
Also you should change:
const [userData, setuserData] = useState("[]");
to:
const [userData, setuserData] = useState([]);
Otherwise you won't be able to loop over it in the JSX.