【问题标题】:wait until first hook is complete before fetching data等到第一个钩子完成后再获取数据
【发布时间】:2021-11-01 10:07:17
【问题描述】:

我有这个自定义钩子,它从 graphql 获取 query.me 数据。 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

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

【问题讨论】:

  • 视情况而定。您用来获取数据的库可能有一个禁用标志,因此如果在条件合适之前运行,请使用它来禁用。或者,您可以根据您的条件在 useEffect 中调用异步函数。

标签: asynchronous react-hooks graphql apollo gqless


【解决方案1】:

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

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;

  ...

【讨论】:

  • 谢谢!这导致React Hook "useQuery" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?
  • 哦,对不起,我回答得太快了,哈哈。您使用什么库进行 useQuery?它可能有一个启用/禁用查询的选项。在这种情况下,您可以通过 !!me
  • 它基于阿波罗
  • 看来您需要使用useTransactionQuery 并将skip 选项设置为!!me gqless.com/react/fetching-data#usetransactionquery
猜你喜欢
  • 2022-10-04
  • 2019-11-02
  • 1970-01-01
  • 2020-10-30
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多