问题描述
我正在关注此Apollo分页教程:
在从服务器或缓存中获取数据之前, data
属性将是未定义的.为避免该错误,请避免破坏 data
直到加载完成,否则请在适当的地方提供默认值:
const {数据: {errorlogsConnection:errorLogs} = {},加载中获取更多,错误,} = useQuery(ERROR_LOG_PAGINATION)
I am following this Apollo Pagination tutorial:
Summary of my issue:
I have a known working GraphQL query that works in the playground. When I try to fetch data and use it in a React component, as outlined in that Apollo link above, I get the following error:
"TypeError: Cannot read property 'errorlogsConnection' of undefined"
However, when I check the response from the graphQL api in the web console, the query does in fact return data. Picture attached below.
I believe I'm probably trying to reference the object incorrectly but I can't spot what my mistake is.
Note: I have been able to query and use this same API endpoint in other React components for this very same project without issue.
Here is the code involved:
I am using this query, which works in my GraphiQL playground:
query errorlogsConnection($cursor: String) {
errorlogsConnection(orderBy: errorid_DESC, first: 4, after: $cursor) {
edges {
node {
errorid
errorlog
entrydate
}
}
pageInfo {
hasPreviousPage
hasNextPage
endCursor
startCursor
}
}
}
Here is the ReactJS code that I've adapted from their tutorial:
function ErrorLogsPagination() {
const {data: {errorlogsConnection: errorLogs}, loading, fetchMore, error} = useQuery(
ERROR_LOG_PAGINATION
);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<ErrorLogs
entries={errorLogs || []}
onLoadMore={() =>
fetchMore({
variables: {
cursor: errorLogs.pageInfo.endCursor
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const newEdges = fetchMoreResult.errorLogs.edges;
const pageInfo = fetchMoreResult.errorLogs.pageInfo;
return newEdges.length
? {
// Put the new comments at the end of the list and update `pageInfo`
// so we have the new `endCursor` and `hasNextPage` values
comments: {
__typename: previousResult.errorLogs.__typename,
edges: [...previousResult.errorLogs.edges, ...newEdges],
pageInfo
}
}
: previousResult;
}
})
}
/>
);
}
The data
property will be undefined until the data is fetched from the server or the cache. To prevent the error, either avoid destructuring data
until after loading is complete, or else provide default values where appropriate:
const {
data: {
errorlogsConnection: errorLogs
} = {},
loading,
fetchMore,
error,
} = useQuery(ERROR_LOG_PAGINATION)
这篇关于JS TypeError:无法读取属性"..."未定义,尽管返回了DATA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!