Reputation: 4033
I am getting the following error after a refresh and sometimes on initial project run:
TypeError: Cannot read property 'statements' of undefined
This is really confusing because the data is rendering fine it just seems the connection fails. Any idea what may be causing the error?
There are no additional errors when I remove the statements.map
I used this medium article to get everything up and running: Medium Article
index.js:
import React, { useState, useReducer } from 'react'
import { useQuery } from '@apollo/react-hooks'
// Custom layout
import Layout from "../components/layout"
import '../sass/styles.scss'
// Data Query
import STATEMENTS_QUERY from '../graphql/statements'
function StatementCall(context) {
const { loading, error, data } = useQuery(STATEMENTS_QUERY, {});
return (
<Layout>
<div className="container">
<div className="row spaces">
<div className="col-md-12">
<p>Testing</p>
{data.statements.data.map((statement, index) => (
<div>
<p>{statement.id}</p>
<p>{statement.title}</p>
</div>
))}
</div>
</div>
</div>
</Layout>
)
}
export default StatementCall
graphql/statements.js:
import gql from 'graphql-tag';
const STATEMENTS_QUERY = gql`
query {
statements(filter: {destination: 1991}) {
data {
id
title
body
}
}
}
`;
export default STATEMENTS_QUERY;
Upvotes: 0
Views: 300
Reputation: 4054
You could check if the results are loading, before you try to render them.
Example:
function StatementCall(context) {
const { loading, error, data } = useQuery(STATEMENTS_QUERY, {});
if (loading) {
return <p>Loading...</p>;
}
if (error) {
// Handle error?
return <p>{error}</p>;
}
return (
<Layout>
<div className="container">
<div className="row spaces">
<div className="col-md-12">
<p>Testing</p>
{data.statements.data.map((statement, index) => (
<div>
<p>{statement.id}</p>
<p>{statement.title}</p>
</div>
))}
</div>
</div>
</div>
</Layout>
)
}
Check the example in useQuery docs.
Upvotes: 1