Issue:
You are receiving an error: Invalid user data: undefined while logging in because the expected user and token data are nested under data in the API response.
Solution:
1.Inspect the API response:
The API returns a response with user and token inside data. Here's the structure:
{
"status": "success",
"message": "Login successful.",
"data": {
"user": { ... },
"token": "eyJ..."
}
}
2.Update handleSubmit in LoginPage.jsx:
Modify the code to access data.user and data.token:
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setError("");
try {
const response = await API.post("/login", formData);
if (response.data?.data?.user && response.data?.data?.token) {
const { token, user } = response.data.data; // Access user and token
localStorage.setItem("token", token); // Save token to localStorage
login(user); // Login with user data
} else {
throw new Error("User data or token is missing in response");
}
} catch (err) {
setError(err.response?.data?.message || "Login failed");
} finally {
setLoading(false);
}
};
3.Explanation:
The API response contains data.user and data.token.
Ensure you access them correctly using response.data.data.user and response.data.data.token.
Add error handling if user or token is missing.
Outcome:
This fix ensures that the user and token data are properly accessed and used for login, resolving the undefined error.
Top comments (0)