该应用程序由 Next.js 运行。我有一个 useQueries 钩子:const userQueries = useQueries({ queries: user.contacts.map((contactId: string) => ({ queryKey: ['contact', conta...
该应用程序由 Next.js 运行。
我有一个 useQueries 钩子:
const userQueries = useQueries({
queries: user.contacts.map((contactId: string) => ({
queryKey: ['contact', contactId],
queryFn: () => getUserById(contactId),
}))
});
api.ts 文件中的函数“getUserById”:
export async function getUserById(userId: string) {
const supabase = createClient();
let {data} = await supabase
.from('users')
.select()
.eq('id', userId);
return data && data[0]
}
我发现当我以这种方式加载数据时,它会按顺序加载而不是并行加载。
我尝试将 api 函数设为非异步,以便每个请求不会等待前一个请求,但 Next.js 禁止在没有“async”前缀的情况下执行服务器操作。有办法解决这个问题吗?
你可以看一下这个 演示 :
interface UserResponse {
firstname: string;
lastname: string;
age: number;
address: string;
email: string;
};
const allFields = {
1: 'firstname' as const,
2: 'lastname' as const,
3: 'age' as const,
4: 'address' as const,
5: 'email' as const
};
type AllFields = typeof allFields;
type AllFieldsKeys = keyof AllFields;
type ToProp<T extends number> = T extends AllFieldsKeys ? AllFields[T]: never;
type FullResult = {
[p in AllFieldsKeys as ToProp<p>] : UserResponse[ToProp<p>]
}
function server<T extends AllFieldsKeys>(fields: T[]): Pick<FullResult, ToProp<T>> {
return fields.reduce((prev: any, curr) => {
// In real life value will probably not be null
return (prev as any)[curr] = null;
}, {});
}
const test = server([1,3,4]);
console.log(test.address); // OK string
console.log(test.firstname); // OK string
console.log(test.lastname); // ERROR
console.log(test.age); // OK number
console.log(test.email); // ERROR
正如其他人提到的,使用数字代替属性名称可能不是一个好主意。如果使用属性名称,代码将更容易理解:
interface AllFields {
firstname: string;
lastname: string;
age: number;
address: string;
email: string;
};
type AllFieldsKeys = keyof AllFields;
type ToProp<T extends keyof AllFields> =
T extends AllFieldsKeys ?
AllFields[T]: never;
function server<T extends AllFieldsKeys>(fields: T[]): Pick<AllFields, T> {
return fields.reduce((prev: any, curr) => {
// Backend will probably return something not null
return (prev as any)[curr] = null;
}, {});
}
const test = server(["address","age"]);
console.log(test.address); // OK string
console.log(test.firstname); // ERROR
console.log(test.lastname); // ERROR
console.log(test.age); // OK number
console.log(test.email); // ERROR