首页 > 解决方案 > 等到第一个钩子完成后再获取数据

问题描述

我有这个query.me从 graphql 获取数据的自定义钩子。该console.log语句显示此挂钩在页面加载时运行了多次,但其中只有 1 次console.logs()包含实际数据。

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 };
};

然后我有另一个钩子,它应该使用上面钩子中的 id 从服务器获取更多数据。

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,
  };
};

我面临的问题是第二个钩子似乎在me仍未定义时调用了第一个钩子,因此出错了。如何配置它,以便仅在me填充值时访问?

我不擅长异步的东西......

标签: asynchronousreact-hooksgraphqlapollogqless

解决方案


如果所需数据不可用,则在第二个挂钩中提前返回。

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;

  ...

推荐阅读