-1

I'm encountering an issue with client-side data fetching in my Next.js 14 application. Specifically, I'm attempting to fetch user profile data from a backend API using Axios within a component, but the data isn't being retrieved.

Expected Behavior: The component should display the user's name on the front-end retrieved from the back-end. Although using Postman, the API call works perfectly fine, and when requesting the server directly on a new tab, it also works and sends back the user data from http://localhost:8080/api/v1/profile. However, using Axios on the front end sends back undefined.

Here's my code:

"use client";
import React, { useState, useEffect } from "react";
import axios from "axios";

const Page = () => {
  const [count, setCount] = useState(null);
  const [userProfile, setUserProfile] = useState(null);

  useEffect(() => {
    const savedValue = localStorage.getItem("jwt");
    setCount(savedValue);
  }, []);

  const getUserProfile = async () => {
    try {
      const token = count;

      if (!token) {
        console.error("No token found in local storage");
        return;
      }

      const response = await axios.get("http://localhost:8080/api/v1/profile", {
        headers: { Authorization: `Bearer ${token}` },
      });

      setUserProfile(response.data);
      // console.log(response); // It always logs undefined
    } catch (error) {
      console.error("Error fetching user profile:", error);
    }
  };

  useEffect(() => {
    getUserProfile()
)
  }, [count]); // Trigger useEffect when count changes (i.e., token retrieval)

  return (
    <div>
      user dashboard: {userProfile && userProfile.name}
    </div>
  );
};

export default Page;

Issue: I'm getting an error where the user profile data is undefined when using Axios to fetch data from the backend API. This occurs even though the request works perfectly fine in Postman and in a new browser tab.

Error Message: The console log shows that the response is always undefined.

Can anyone help me resolve this issue? Any advice on what might be causing the data not to be retrieved in my Next.js application?

Thank you in advance!

1 Answer 1

0

Check localStorage.getItem('jwt') is null or string.

And for token, you can use axios's request interceptor make code easier:

'use client';
import React, { useState, useEffect } from 'react';
import axios from 'xior';

function getToken() {
  return localStorage.getItem('jwt');
}

axios.interceptors.request.use((config) => {
  const token = getToken();
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
});

const Page = () => {
  const [userProfile, setUserProfile] = useState(null);

  const getUserProfile = async () => {
    try {
      const response = await axios.get('http://localhost:8080/api/v1/profile');
      setUserProfile(response.data);
      // console.log(response); // It always logs undefined
    } catch (error) {
      console.error('Error fetching user profile:', error);
    }
  };

  useEffect(() => {
    if (getToken()) {
      getUserProfile();
    }
  }, []); // Trigger useEffect when count changes (i.e., token retrieval)

  return <div>user dashboard: {userProfile && userProfile.name}</div>;
};

export default Page;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.