I am currently using GraphQL to query my WordPress server which I'm using as a backend.
Everything is working as it should be so far, this is my graphQL query:
const GET_ALL_MEDIA = gql`
query MyQuery {
slumpMedias(first: 100) {
edges {
node {
title
slumpMeta {
image {
mediaItemUrl
}
audio1 {
mediaItemUrl
}
}
}
}
}
}
`;
function Items() {
const { loading, error, data } = useQuery(GET_ALL_MEDIA);
return (
<div>
<h2>{data.slumpMedias.edges[5].node.title}</h2>
</div>
);
}
This renders perfectly, and I can see the correct title rendered in front of me.
Now That I have access to the nodes that I need I would like to start building a new data structure above the JSX. My only issue is that when I start construct this object and make the same reference, my program crashes to an empty screen.
This is the difference in code:
function Items() {
const { loading, error, data } = useQuery(GET_ALL_MEDIA);
console.log(data);
const objects = [
{
id: 0,
title: data.slumpMedias.edges[6].node.title,
image: "/images/1.png",
sound: "https://google.com",
items: [],
},
];
return <Display objects={objects}></Display>;
}
I notice that the title does update briefly leading me to believe that the reference is correct, it's just that on refresh I'm met with a blank screen.
The error message:
Items.js:35 Uncaught TypeError: Cannot read properties of undefined (reading 'slumpMedias')
at Items (Items.js:35:1)
at renderWithHooks (react-dom.development.js:16175:1)
at mountIndeterminateComponent (react-dom.development.js:20913:1)
at beginWork (react-dom.development.js:22416:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
at invokeGuardedCallback (react-dom.development.js:4274:1)
at beginWork$1 (react-dom.development.js:27405:1)
at performUnitOfWork (react-dom.development.js:26513:1)
at workLoopSync (react-dom.development.js:26422:1)
How can it suddenly be unable to read Custom Post Type on WordPress when I was making the exact same reference as before except in the JSX?
The issue was due to order of operations
data is undefined while the query is still loading or has an error, here is the correct syntax:
Cannot destructure GraphQL query as apollo-client is undefined?
I have also revised my technique within this answer to de-structure the object correctly