【发布时间】: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