When the journal page is first loaded the entries are not displayed and it says that user is null, which leads to an error, which says GET http://localhost:4000/getentries 400 (Bad Request). However, when console logging user after if(user) it displays the information for user. Additionally, whenever I reload/refresh the page, the entries for the user are displayed.
Journal page
const Journal = () => {
const [entries, setEntries] = useState([]);
const { user } = useContext(UserContext);
useEffect(() => {
if (user) {
handleDisplay(user.id);
}
}, [user]);
const handleDisplay = async (userID) => {
try {
const res = await axios.get("/getentries", { params: { userID } });
setEntries(res.data);
} catch (err) {
console.log(err);
}
};
return (<></>);
};
export default Journal;
get request
app.get("/getentries", async (req, res) => {
try {
const { userID } = req.query;
if (!userID) {
return res
.status(400)
.json({ error: "userID parameter is missing or invalid" });
}
const entries = await Entry.find({ userID });
res.json(entries);
} catch (err) {
console.error("Get entries error:", err);
res.status(500).json({ error: "Internal server error" });
}
});
UserContext
export const UserContext = createContext({});
export function UserContextProvider({ children }) {
const [user, setUser] = useState(null);
useEffect(() => {
const fetchUserProfile = async () => {
try {
const { data } = await axios.get("/profile");
setUser(data);
} catch (err) {
console.log(err, "An error occurred");
} finally {
}
};
fetchUserProfile();
}, []);
return (
<UserContext.Provider value={{ user, setUser, loading }}>
{children}
</UserContext.Provider>
);
}
I’ve tried to put handle display in useEffect and call it in useEffect to try and make it so if user is changed, then handleDisplay is called. However, this still leads to the same issue.
BlaZeZ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.