On my page, there is a sidebar that displays items by fetching data successfully. However, when I click on one of the sidebar items to pass props to another component for fetching data, it doesn't fetch any data until I manually click the refresh button. I am using Tanstack React Query for fetching and caching:
This is how my page looks like with working fetch:
"use client";
import { useSession } from "next-auth/react";
import { useQuery } from "@tanstack/react-query";
import React, { useState } from "react";
import StudentSubjects from "@/app/components/StudentSubjects"
import Link from "next/link";
interface SubjectData {
id: string;
name: string;
description: string;
}
const Student: React.FC = () => {
const { data: session, status } = useSession();
const { data: subjectsData, isLoading, error } = useQuery<
{ studentData: { whatsapp: string; name: string; grade: string; subjects: string[] } },
Error
>({
queryKey: ["subjects"],
queryFn: async () => {
if (status === "authenticated") {
const userEmail = session?.user?.email;
const res = await fetch(`/api/getStudent?email=${userEmail}`);
const data = await res.json();
return data;
} else {
return { studentData: { whatsapp: "", name: "", grade: "", subjects: [] } };
}
},
staleTime: Infinity,
gcTime: 60000,
enabled: status === "authenticated",
});
const [selectedSubject, setSelectedSubject] = useState<SubjectData | null>(null);
const subjectsList: SubjectData[] = subjectsData.studentData.subjects.map((subject) => {
const [id, name, description] = subject.split(",");
return { id, name, description };
});
return (
<div className="flex">
...
This is the code for my StudentSubjects component:
"use client";
import { useSession } from "next-auth/react";
import { useQuery } from "@tanstack/react-query";
// Code for SubjectDetails component ...
I am facing an issue where the fetching is not happening automatically in the component, but only after clicking the refetch button. This behavior is unexpected, and I need help understanding why this occurs. What could be causing the problem, and what steps can I take to resolve it?