wait until first hook is complete before fetching data

Viewed 350

I have this custom hook which fetches the query.me data from graphql. The console.log statement shows that this hook is running a number of times on page load, but only 1 of those console.logs() contains actual data.

import { useCustomQuery } from '../api-client';

export const useMe = () => {
  const { data, isLoading, error } = useCustomQuery({
  query: async (query) => {
      return getFields(query.me, 'account_id', 'role', 'profile_id');
    },
  });
  console.log(data ? data.account_id : 'empty');

  return { isLoading, error, me: data };
};

I then have this other hook which is supposed to use the id's from the above hook to fetch more data from the server.

export const useActivityList = () => {
  const { me, error } = useMe();

  const criteria = { assignment: { uuid: { _eq: me.profile_id } } } as appointment_bool_exp;

  const query = useQuery({
    prepare({ prepass, query }) {
      prepass(
        query.appointment({ where: criteria }),
        'scheduled_at',
        'first_name',
        'last_name',
      );
    },
    suspense: true,
  });

  const activityList = query.appointment({ where: criteria });

  return {
    activityList,
    isLoading: query.$state.isLoading,
  };
};

The problem I am facing is that the second hook seems to call the first hook when me is still undefined, thus erroring out. How do I configure this, so that I only access the me when the values are populated?

I am bad with async stuff...

1 Answers

In the second hook do an early return if the required data is not available.

export const useActivityList = () => {
  const { me, error } = useMe();

  if (!me) {
    return null;
    // or another pattern that you may find useful is to set a flag to indicate that this query is idle e.g.
    // idle = true;
  }

  const criteria = { assignment: { uuid: { _eq: me.profile_id } } } as appointment_bool_exp;

  ...
Related