I’m working on a React
and Redux
application where I fetch the user’s profile details after successful authentication. The id
is being fetched correctly from the useParams
hook, but the user data is not displaying as expected.
Here’s a breakdown of my setup:
-
Auth Context: I’m using a context provider to manage authentication states and store the token in
localStorage
. The token is being retrieved and decoded properly. -
Redux Actions: The
fetchProfile
action makes an API call to get the user’s profile using Axios.export const fetchProfile = () => async (dispatch) => { dispatch({ type: SET_PROFILE_LOADING, payload: true }); try { const { data } = await axios.get(`${API_URL}/user/me`); dispatch({ type: FETCH_PROFILE, payload: data }); } catch (error) { handleError(error); } finally { dispatch({ type: SET_PROFILE_LOADING, payload: false }); } };
-
Redux Reducer: The reducer updates the state with the fetched profile data.
case FETCH_PROFILE: return { ...state, user: { ...state.user, ...action.payload, }, };
-
Component: In the
AccountDetails
component, I fetch the user profile if the user is authenticated.useEffect(() => { if (isAuthenticated) { dispatch(fetchProfile()); } else { console.warn("Token is null when trying to fetch profile."); } }, [dispatch, isAuthenticated]); useEffect(() => { console.log(user); // Debugging user data }, [user]);
However, the issue is that the user
object from Redux state is either undefined
or incomplete, even though the id
from the URL (useParams
) is fetched correctly, and the API call for fetching the profile seems successful. I’ve verified that:
- The API is returning the correct data in the response.
- The token is being sent with the request header.
- The
FETCH_PROFILE
action is being dispatched.
What I’ve tried:
- Logging the
user
state to check its value—it’sundefined
initially and doesn’t update. - Verifying the API response directly in the network tab.
- Ensuring the reducer updates the state correctly.
- Confirming that
fetchProfile
is called when the component mounts.
Any help or suggestions to resolve this issue would be greatly appreciated. Let me know if more details are needed!