DEV Community

Wahid
Wahid

Posted on

1 1

How to fix Invalid User Data in Login API Response

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..."
  }
}
Enter fullscreen mode Exit fullscreen mode

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);
  }
};

Enter fullscreen mode Exit fullscreen mode

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)