Data is not getting fetched before rendering component

  javascript, reactjs

I am able to build login functionality with react + springboot + postgres. After login, when JWT is stored in localstore, my app redirects to /profile page for which I am rendering <Profile /> component, which looks like this:

Profile.js

import React, { useState, useEffect } from "react";
import UserDataService from '../services/user.services'

export default function ProfileModule(props) {

    const [userDetails, setUserDetails] = useState(undefined);

    const retrieveUserDetails = () => {
        console.log('Retrieving data')
        UserDataService.getUserDetails()
          .then(response => {
            setUserDetails(response.data);
            console.log(response.data);
          })
          .catch(e => {
            console.log(e);
          });
      };

    useEffect(() => {
        retrieveUserDetails();
    }, []);
      
    return (
        <div style={{paddingLeft:50, marginTop: -20}}>
            <h1> Welcome {userDetails.firstName + " " + userDetails.lastName} + "," </h1>
            <br />
            User Name: {userDetails.userName}
            <br />
            Phone Number: {userDetails.phone}
            <br />
            Email: {userDetails.email}
        </div> 
    )
}

But while rendering above component, I am getting

TypeError: Cannot read property 'firstName' of undefined
ProfileModule
../client/src/components/Profile.js:26
  23 |   
  24 | return (
  25 |     <div style={{paddingLeft:50, marginTop: -20}}>
> 26 |         <h1> Welcome {userDetails.firstName + " " + userDetails.lastName} + "," </h1>
     | ^  27 |         <br />
  28 |         User Name: {userDetails.userName}
  29 |         <br />

Somehow userDetails is not getting populated. I debugged in chrome with breakpoints on retrieveUserDetails and useEffect and also on user.services.getUserDetails(). But no breakpoint is getting hit. Also none of those console.log()s are visible. What I am missing?

user.services.js

import axios from "axios";
import authHeader from "./auth-header";

const API_URL = "http://localhost:8080/api/test/";

const getUserDetails = () => {
    const user = JSON.parse(localStorage.getItem('user'));
    return axios.get(API_URL + "userdetails/" + user.username, { headers: authHeader() } );
}

export default {
  getUserDetails,
};

(I tested the end point http://localhost:8080/api/test/userdetails/username in Postman and it is retrieving the details.)

Source: Ask Javascript Questions

LEAVE A COMMENT