Blessing
Blessing

Reputation: 2720

How do I make dependent queries in react-query?

I have a component called Sidebar.tsx that is fetching some data here but I want to only fetch levels only if studentId is available. I looked through dependent queries on react-query documentation . I applied that in my code but it looks like it doesn't work. Here's is what I did.

First of all I fetched the studentId from an API too, here is how it looks like:

  const studentId = intakeProgramStore.getStudentShipByUserId(authUser?.id)
.data?.data.data[0];

Now another function to get programs

class IntakeProgramStore{

  getIntakeProgramsByStudent(studentId: string) {
    return useQuery(
      ['intakeProgram/studentId', studentId],
      () => intakeProgramService.getIntakeProgramsByStudent(studentId),
      { enabled: !!studentId },
    );
  }
}

export const intakeStore = new IntakeProgramStore();

This function is located in stores/intake.store.ts and what it does is that when it gets called it calls a service method called intakeProgramService.getIntakeProgramsByStudent which is also imported at the top and it works fine as expected. The problem I have here is that it is calling that service even if studentId is undefined while it was supposed to call it when it has a value.

Here's how I'm calling it inside Sidebar.tsx which is my UI component

 const programs = intakeProgramStore.getIntakeProgramsByStudent(student.id)
.data?.data.data[0];

I moved the code that was in the stores/intake.store.ts file into Sidebar.tsx and now it worked fine but I don't know why. Here's how it looks

const programs = useQuery(
['intakeProgram/studentId', student?.id],
() => intakeProgramService.getIntakeProgramsByStudent(student?.id),
{ enabled: !!student

I'm not sure why it's not working when I'm fetching inside the store but works when I do it in the UI component.

Upvotes: 2

Views: 2867

Answers (1)

TkDodo
TkDodo

Reputation: 28733

Generally, your code looks correct. The only thing that I can see is that in the first example, you're calling useQuery inside a function called getIntakeProgramsByStudent, which is an invalid hook call. Hooks can only be called:

  • by functional react components
  • inside custom hooks, which are functions that start with use....

see also the rules of hooks react documentation.

A custom hook for your useQuery call would be:

export const useIntakeProgramsByStudent(studentId: string) {
  return useQuery(
    ['intakeProgram/studentId', studentId],
    () => intakeProgramService.getIntakeProgramsByStudent(studentId),
    { enabled: !!studentId },
  );
}

Upvotes: 2

Related Questions