Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello! I'm developing a React app with Nodejs backend and I've come across a problem. The app is for a language centre and it allows a client to log in and click on their profile to see the courses to which they have enrolled. To store the user's id, email and name, I used an "AuthContext", which I am now using in order to get the courses of a certain user, by their id. The problem is, I get the correct id and the corresponding courses when I first access the page, but after I click refresh, the id turns to 0 and the courses aren't displayed anymore, although I continue to be logged in and have all the correct user data, including the id (I have the data displayed somewhere and the id never changes). Any help would be much appreciated, thank you!

What I have tried:

This is where I make the get request and where I should get the courses

const { authState } = useContext(AuthContext);
const id = authState.id;
console.log(authState.id + " id");
const [listOfCourses, setListOfCourses] = useState([]);

useEffect(() => {
axios.get(`http://localhost:3001/users_courses/${id}`, {
headers: {
accessToken: localStorage.getItem("accessToken"),
}
}).then((response) => {
setListOfCourses(response.data);
});

return (

{listOfCourses.map((course) =>
{course.CourseId}
)}

)


This is the router which accesses the database. The validate token just checks to see if the user is logged in and there are no problems with that in this context.

router.get("/:userId", validateToken, async(req, res) => {
const userId = req.params.userId;
console.log(userId + ' looking for this user');
const list = await Users_Courses.findAll({ where: { UserId: userId } });
console.log(list);
res.json(list);
});
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900