Trying to display the information from the response but it won't show up. Using mongoose and nextjs (typescript)

Viewed 46

Trying to display the information from the response but it won't show up. If I console log it i can see it in the terminal. how do i get it to show on the page? the response displays as an array

type Student = {
  _id: string;
  firstname: string;
  lastname: string;
  matricno: string;
};

function DashBoard() {
  const [student, setStudent] = useState<Student>();

  //this works
  // console.log(getCookie("user"))

  const showinfo = async () => {
    const token = getCookie('user');
    const body = {
      _id: token,
    };

    const response = (await fetch(
      'http://localhost:3000/api/student/fetchStudent',
      { method: 'POST', body: JSON.stringify(body) }
    ).then((res) => res.json())) as Student;

    console.log(JSON.stringify(response, ['student', 'firstname'])); //displays right information

    setStudent(response);

    const user = JSON.stringify(response, ['student', 'lastname']);

    console.log(user); //displays right information
  };

  useEffect(() => {
    showinfo();
  }, []);

  return (
    <StuLayout>
      <>
        <Header title='dashboard' />
        <div className='text-red-500 text-3xl'>
          welcome {student?.firstname}
        </div>
      </>
    </StuLayout>
  );
}

export default DashBoard;
1 Answers

i had to restructure the api to specify the elements i needed

export default async function fetchStudent(req, res) {
if (req.method === "POST") {
    console.log('CONNECTING TO MONGO');
    await connectMongo();
    console.log('CONNECTED TO MONGO');

    const { _id } = JSON.parse(req.body)

    console.log('FETCHING DOCUMENTS');




    const student = await Student.findById(_id).select("lastname firstname ");

    console.log('FETCHED STUDENT');
    // console.log(student)
    return res.status(200).json({
        ...student._doc,

    })
}
else {

    return res.status(400).json({
        notFound: true,
    });

}

};

Related