MERN Stack: User Data Not Available in Context After Login

I’m building a contact form in my MERN stack application, but I’m having trouble accessing the user data from the authentication context. I can see the token is being stored in localStorage, and the user is logged in, but the user data is undefined whe…


This content originally appeared on DEV Community and was authored by Hashim KHAN

I'm building a contact form in my MERN stack application, but I'm having trouble accessing the user data from the authentication context. I can see the token is being stored in localStorage, and the user is logged in, but the user data is undefined when I try to use it in my ContactMe component.

Here's the relevant part of my code:

Auth.jsx (Authentication Context):

import { createContext, useContext, useState, useEffect } from "react";

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [token, setToken] = useState(localStorage.getItem("token"));
const [user, setUser] = useState("");

const userAuthentication = async () => {
try {
const response = await fetch("http://localhost:5000/api/auth/user", {
method: "GET",
headers: {
Authorization: Bearer ${token},
},
});

  if (response.ok) {
    const data = await response.json();
    setUser(data.userData);
  } else {
    console.error("Error fetching user data");
  }
} catch (error) {
  console.log(error);
}

};

useEffect(() => {
userAuthentication();
}, []);

return (

{children}

);
};

export const useAuth = () => {
return useContext(AuthContext);
};`

ContactMe.jsx (Contact Form Component):

`import React, { useState } from 'react';
import { useAuth } from "../store/Auth";

const defaultContactFormData = {
username: "",
email: "",
message: "",
};

export const ContactMe = () => {
const { user } = useAuth();
const [data, setData] = useState(defaultContactFormData);

if (user && user.email) {
    console.log("User email:", user.email);
} else {
    console.log("User data is not available or email is missing");
}

// ...rest of your component code

};
Problem: When the ContactMe component renders, the user data is undefined, and I get the console log stating "User data is not available or email is missing." I expected the user data to be available after successful authentication.

What I Tried: I checked the token is being stored correctly in localStorage and is being used to fetch user data from the backend. I verified that the userAuthentication function is called in the useEffect hook to fetch user data after the component mounts. I confirmed that the backend is returning the user data correctly. What I Expected: I expected the user object to be populated with user data (including email) in the ContactMe component after a successful login, but it remains undefined, leading to the message "User data is not available or email is missing."

Question: Why is the user data not available in the ContactMe component? How can I ensure that the user data is correctly fetched and passed to components that need it? Any insights or suggestions would be greatly appreciated!


This content originally appeared on DEV Community and was authored by Hashim KHAN


Print Share Comment Cite Upload Translate Updates
APA

Hashim KHAN | Sciencx (2024-08-13T06:41:16+00:00) MERN Stack: User Data Not Available in Context After Login. Retrieved from https://www.scien.cx/2024/08/13/mern-stack-user-data-not-available-in-context-after-login/

MLA
" » MERN Stack: User Data Not Available in Context After Login." Hashim KHAN | Sciencx - Tuesday August 13, 2024, https://www.scien.cx/2024/08/13/mern-stack-user-data-not-available-in-context-after-login/
HARVARD
Hashim KHAN | Sciencx Tuesday August 13, 2024 » MERN Stack: User Data Not Available in Context After Login., viewed ,<https://www.scien.cx/2024/08/13/mern-stack-user-data-not-available-in-context-after-login/>
VANCOUVER
Hashim KHAN | Sciencx - » MERN Stack: User Data Not Available in Context After Login. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/13/mern-stack-user-data-not-available-in-context-after-login/
CHICAGO
" » MERN Stack: User Data Not Available in Context After Login." Hashim KHAN | Sciencx - Accessed . https://www.scien.cx/2024/08/13/mern-stack-user-data-not-available-in-context-after-login/
IEEE
" » MERN Stack: User Data Not Available in Context After Login." Hashim KHAN | Sciencx [Online]. Available: https://www.scien.cx/2024/08/13/mern-stack-user-data-not-available-in-context-after-login/. [Accessed: ]
rf:citation
» MERN Stack: User Data Not Available in Context After Login | Hashim KHAN | Sciencx | https://www.scien.cx/2024/08/13/mern-stack-user-data-not-available-in-context-after-login/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.