asynchronous - 等到第一个钩子完成后再获取数据
问题描述
我有这个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
填充值时访问?
我不擅长异步的东西......
解决方案
如果所需数据不可用,则在第二个挂钩中提前返回。
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;
...
推荐阅读
- ionic-framework - 无法显示来自环回服务器的图像
- java - 如何等待订阅完成?
- c# - 在编辑记录中获取下拉值
- javascript - 从 Cheerio 解析的 html 文件中获取工具提示文本
- prolog - 序言切“!” erlang中的运算符
- java - 将 Spring Boot WebMvcConfigurer 限制为仅指定路径
- java - 如何在使用 prod 数据库时停止 java 实体以获取保存#java
- r - 按特定列分组并在 Python 中使用 dplython 汇总行数
- javascript - 如何在不使用叠加层的情况下标记开放层中的特征
- ruby-on-rails - 如何更改 Rspec 中的默认控制器?