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

Transforming the string attribute of an object within a JavaScript array through mapping

Here is an array of objects: { "attr1": 123, "attr2": "a.end", }, { "attr1": 123, "attr2": "b.start", } The task is to remove the first part of the attr2 string up to and including the '.& ...

The type 'function that takes in a CustomEvent and returns void' cannot be assigned to a parameter of type 'EventListenerOrEventListenerObject'

When I upgraded from TypeScript version 2.5.3 to 2.6.1, my custom event setup started giving me an error. window.addEventListener('OnRewards', (e: CustomEvent) => { // my code here }) [ts] Argument of type '(e: CustomEvent) => vo ...

Displaying images in Ionic from a JSON URL source

I am having trouble getting an image from a JSON to display on an Ionic card. Although I can see the JSON response in the console log, the image is not showing up on the card, leaving it blank. It seems like I'm making a mistake in the HTML code. Any ...

Are there any alternatives to Next.JS router.query in the form of an App Router version?

Currently, I am tackling a project that involves utilizing the updated Next.JS app router. However, I am encountering difficulties in obtaining the URL slug. In the past with the original Page Router (next/router), retrieving the slug was as simple as: co ...

Issues with incorrect source path in Typescript, Gulp, and Sourcemaps configuration

In my nodejs app, the folder structure is as follows: project |-- src/ | |-- controllers/ | | |`-- authorize-controller.ts | |`-- index.ts |--dist/ | |--controllers/ | | |`-- authorize-controller.js | | |`-- authorize-controller.js.map | ...

Performing bulk operations on all selected rows in a table using Angular 6

Within my Angular 6 web application, there is a table with checkboxes in each row. My goal is to be able to perform bulk actions on the selected rows, such as deleting them. One approach I considered was adding an isSelected boolean property to the data m ...

"Encountering another disappointing build failure due to an unhelpful error

During the process of moving a project from Heroku to Vercel to utilize Next.js, I encountered a strange bug that I've never seen before, despite previous experience with Next. I successfully built it last night and everything was functioning properl ...

Determine in React whether a JSX Element is a descendant of a specific class

I am currently working with TypeScript and need to determine if a JSX.Element instance is a subclass of another React component. For instance, if I have a Vehicle component and a Car component that extends it, then when given a JSX.Element generated from ...

New content appears in Material UI v4 Textfield after being typed

One interesting issue I'm facing is with a list of TextFields on the page where users can input text. The variable data holds the dataset. The problem is, as shown in the gif below, there is a delay in displaying the text after the user types. I initi ...

Reimagine server-side storage options as an alternative to remixing JavaScript local storage

My remix application is designed to serve as a frontend. I retrieve data from the backend and sometimes need to load specific data only once and reuse it across multiple pages. In our previous frontend setup, we utilized localstorage; however, with the cur ...

The Image component in a test within Next.js was not wrapped in an act(...) during an update

After setting up a basic NextJS app with create-next-app and integrating Jest for testing, I encountered an error message stating "An update to Image inside a test was not wrapped in act(...)". The issue seems to be related to the Image component in NextJS ...

Using localStorage in the client side of nextJS is a breeze

Encountering an error while attempting to retrieve local storage data. Even with the use client directive in place at the beginning, the issue persists. 'use client'; const baseURL = 'https://localhost:7264'; const accessToken = localSt ...

What is the reason behind the lag caused by setTimeout() in my application, while RxJS timer().subscribe(...) does not have the same

I am currently working on a component that "lazy loads" some comments every 100ms. However, I noticed that when I use setTimeout for this task, the performance of my application suffers significantly. Here is a snippet from the component: <div *ngFor ...

Displaying error messages in React Hook Form when passing state

After reviewing the responses below, I have updated my code as follows: import { useState } from "react"; import Head from "next/head"; import Link from "next/link"; import Image from "next/image"; import Background ...

Transforming an ordinary JavaScript object into a class instance

As I was delving into Angular's documentation on "Interacting with backend services using HTTP", I came across the following statement in the "Requesting a typed response" section: ...because the response is a plain object that cannot be automatical ...

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

Navigating the maze of Material UI in React with TypeScript

I have a functioning code, but I am trying to incorporate Material UI into it. However, when I replace 'input' with 'TextField', I encounter the following error: Uncaught (in promise) Error: Request failed with status code 422 at cr ...

New bug found in Next.js 13.5.4: Parent loading page is interfering with child loading page

Currently, I am utilizing Next.js version 13.5.4 with the app router. My goal is to configure distinct loading.tsx components for each page. However, the issue I am facing is that the style from the parent loading.tsx persists while rendering nested page ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

I possess a JSON array object and need to identify and extract the array objects that contain a specific child node

const jsonArray = { "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "members": [ { "name": "Molecule Man", "age": 29, "secretIdent ...