Is the client component not initializing the fetch operation?

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?

Answer №1

Upon examination, it appears that the component is not fetching data anywhere other than in the refetch function, which is only triggered by your button click. In the initial Page/Component, you have

  const subjectsList: SubjectData[] = subjectsData.studentData.subjects.map((subject) => {
    const [id, name, description] = subject.split(",");
    return { id, name, description };
  });

to populate the data. However, this code is missing in the second component. One approach could be to include a call to fetch data, either directly or using useEffect. For example:

useEffect(() => {
  if (refetch) {
    refetch()
  }
}, [refetch]);

This way, the data would be fetched when useQuery triggers it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting the selection in the Dropdown Box

I've been attempting to assign a value to the select box as shown below: <dx-select-box [items]="reportingProject" id="ReportingProj" [text]="reportingProject" [readOnly]="true" > ...

Guide to creating a type for a JSON object with nested properties in TypeScript

I have some JSON strings structured as follows: { name: 'test', url: 'http://test.org', contact: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0263636342766771762c616d6f" ...

The absence of the head tag in the view source is a known issue related to Next.js

I have created a Next.js app where I implemented my head tag. However, when I check the view source by right-clicking, I don't see my title and meta tags there. How can I achieve that? Even though the head tag is missing in view source, it can be fou ...

The nz-switch function is malfunctioning as a result of an update that has affected its value

<form [formGroup]="businessFoodHygieneForm"> <div class="box p-4 d-flex jc-between ai-center"> <span> Food Hygiene Link </span> <label> <nz-switch class="switch- ...

Issue: Vue TypeScript module not foundDescription: When using

Is there anyone out there who can assist me with this issue regarding my tsconfig.json file? { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": " ...

The deployment of my Next.js app on Heroku was refused due to an incompatible Node version

Encountering issues while attempting to deploy my app on Heroku, I am faced with the following shortened errors: remote: -----> Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL=error remote: NODE_VERBOSE=false remot ...

The MUI Link embedded in my Next.js 13 project is not functioning properly within an IconButton

// packages/webapp/src/app/(authenticated)/_components/Sidebar/index.tsx "use client"; import React from 'react'; import { Box, Avatar, IconButton, Button, Stack } from '@mui/material'; import PaperContainer from '@/app/_ ...

Setting up Authorization for FETCH requests in NEXT.js using .env.local

`export default function reservations() { let [reservationStock, setReservationStock] = useState([]); useEffect(() => { fetch(url, { headers: new Headers({ Authorization: "MyBasic Credentials", " ...

Classname fails to modify the base style of the AppBar

Struggling to modify the appearance of the AppBar component by utilizing the className attribute, however, the .MuiAppBar-root class consistently takes precedence. const useStyles = makeStyles((theme: Theme) => ({ appBar: { backgroundColor: &apos ...

Troubleshooting Problems with Deploying Next Js on Firebase

I am currently working on a new Next Js application and have successfully deployed it on Vercel by linking the GitLab project. Now, I need to deploy the same project on Firebase. Here's what I have tried so far: - Ran firebase init This command gen ...

Making all requests server-side in Next.JS: A step-by-step guide

I am in the process of creating a Next.JS application that will be retrieving data from both a Python API and a Postgres Database. Although this task may seem straightforward, the project requirements dictate that all requests must originate from the serv ...

Having difficulty subscribing to multiple observables simultaneously using withLatestFrom

I am facing an issue where I have three observables and need to pass their values to a service as parameters. I attempted to do this using WithLatestFrom(), but it works fine only when all values are observables. this.payment$.pipe( withLatestFrom(this.fir ...

transform json array into a consolidated array by merging identical IDs

I need to transform an array into a different format based on the values of the ID and class properties. Here is the initial array: const json = [{ "ID": 10, "Sum": 860, "class": "K", }, { "ID": 10, "Sum": 760, "class": "one", }, { "ID": ...

the usequery function is unable to correlate the information

I have made a request to my backend API. import { instance } from '../api/ApiProvider'; export default async function fetchCurrency() { return instance.get(`api/Currency`); } Then, I am utilizing the useQuery hook. const { data } = useQuery([ ...

Using the Async feature, I can retrieve the value of a string type when the return type of a function is Promise<any>

While working on a custom pipe, I encountered a situation that puzzled me. Can you explain why the code snippet below is considered valid? async transform(value: any): Promise<string> { let fullNameBasedOnPreference: string; fullNameBasedOnP ...

Discovering specific values for an ID using API calls in Angular (Implementing CRUD Operations in Angular with API Integration)

My current project involves CRUD operations in Angular utilizing the API created in Laravel. I have successfully added and fetched values, but encountered an issue when attempting to update values using their respective IDs. This snippet is from my app.co ...

What is the most effective way to share data among components in React?

I recently delved into learning about react and find myself puzzled on how to pass data between two components. Presently, I have set up 2 functions in the following manner: First, there's topbar.tsx which displays information for the top bar, inclu ...

The Swiper API's width seems to be expanding endlessly

Is there a known issue with Swiper when attempting to set the flex-col direction? The width seems to exceed limits and does not stop from expanding, resulting in an incredibly large width like '33599999999px' when inspecting the page. Here is th ...

The sanitizer variable becomes null when accessed outside of the NgOnInit function in Angular using TypeScript

At first, I added DomSanitizer to the component: import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser'; Next, a class was created and included in the constructor: export class BlocklyComponent implements OnInit { primar ...

Issue detected in rxjs-compat operator's shareReplay file at line 2, column 10:

I've encountered an issue with the angular material spinner I'm using in my project. The error message is as follows: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): error TS2305: Module '"D:/ControlCenter/ofservices ...