skip to Main Content

i want to display data on the page but getting and error : data is not defined. please look on the code and help me

import { useEffect } from "react";
import axios from "axios";
import useLatestPosts from "../../hooks/useLatestPosts";
import { useRouter } from 'next/router'
import Head from "next/head";
export const Profile = ({ po }) => {
const { latestPosts } = useLatestPosts();
const router = useRouter()
const username = router.query
const fetchUserData = async () => {
    const { data } = await axios.get(`http://localhost:8000/api/profile/${username.slug1}`)
    console.log("data", data);

}
useEffect(() => {
    fetchUserData()
}, [])

return (
    <>
        <Head>
            <title>{username.slug1}</title>
        </Head>
        <div>
            <h1>Profile Name</h1>
            {data.map((user)=>(
              <li key={user.id}>
               <h1>{user.name}</h1>
              </li>
            ))
           }

        </div>

    </>
);
};

export default Profile;

data is displaying in console in the object form when i comment jsx code but then i un-comment jsx code it again shows me "data is not defined"

2

Answers


  1. Chosen as BEST ANSWER
     const [users, setUsers] = useState([]);
    const fetchUserData = async () => {
        const { data } = await axios.get(`http://localhost:8000/api/profile/${username.slug1}`)
        setUsers(data)
        console.log(data)
    
    }
    useEffect(() => {
        fetchUserData()
    }, [])
    
    return (
        <>
            <Head>
                <title>{username.slug1}</title>
            </Head>
            <div>
                <h1>Profile</h1>
                {users.length > 0 ? (
                    <div>
                        {users.map((profile) => (
                            <div>
                                <h2>{profile.user.name}</h2>
                            </div>
                        ))}
                    </div>
                ) : (
                    <p className="loading">Loading... </p>
                )}
    

  2. You’re trying to use the data variable inside your JSX, but it is not defined anywhere in your component. You can define it in your component’s state:

    ...
    const [data, setData] = useState([]);
    
    const fetchUserData = async () => {
      const { data } = await ...
      setData(data);
    }
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search