![](/img/trans.png)
[英]Fetching data from GraphQL server via react(ApolloClient.query()) method
[英]GraphQL query not fetching successfully in React
我嘗試在 React 中使用 GraphQL
useQuery
api 像這樣:
const {loading, data, error} = useQuery<BaseUser, BaseUserVars>(
GET_DASHBOARD_USER,
{variables: {id: "1"}}
)
在我的 API 文件夾中,我保存了所需的接口和查詢,如下所示:
export interface BaseUser {
id: string
username: string
age: number
goal: Goal
tasks: [{
id: string,
description: string,
completedAt: string | null,
expirationDate: string
}]
}
export interface BaseUserVars {
id: string
}
export const GET_DASHBOARD_USER = gql`
query userWithTasks($id: String!){
user(id: $id){
id
username
biography
goal
tasks {
id
description
completedAt
expirationDate
}
}
}`
運行查詢時出現400 bad response
錯誤。 我嘗試調用一個函數,該函數已在我的后端解析器中定義,名為userWithTask
在操場上,我在沒有query
關鍵字的情況下使用了它,它運行良好:
{
userWithTasks(id: "1"){
id
username
biography
goal
tasks {
id
description
completedAt
expirationDate
}
}
}
語法應該是正確的,有什么問題?
更新:
這是我收到的錯誤消息Cannot query field "user" on type "Query". Did you mean "users"?
Cannot query field "user" on type "Query". Did you mean "users"?
這是我的后端解析器以供參考:
@Query(() => User)
async userWithTasks(@Args("id") id: string): Promise<User> {
const user = await this.userService.getUserByIdWithTasks(id);
console.log(user)
return user
}
您的查詢字段中不存在用戶。 在操場上,您調用 userWithTasks 而不是 user。 當您在 gql 時發出請求時,您必須首先使用鍵入的參數“復制”字段,然后使用參數值“復制”字段。
export const GET_DASHBOARD_USER = gql`
query userWithTasks($id: String!){
userWithTasks(id: $id){
id
username
biography
goal
tasks {
id
description
completedAt
expirationDate
}
}
}`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.