Hey guys, I'm having an issue trying to fetch data from my backend CMS. A while back it was working and still it working on production, but attempting to load up the dev server I'm met with that message. It seems to be an issue of accessing a variable before the data is initialized. I've tried a few things, but not sure what I'm doing wrong.
My Setup:
Frameworks: Astro & React
Backend: DatoCMS
Fetching method: GraphQL
index.astro
`
import Layout from '@components/layout.astro'
import useQuery from '@queries/client'
import { QUERY_HOMEPAGE } from '@queries/queries'
let title = 'Homepage'
const { data } = await useQuery(QUERY_HOMEPAGE)
const homepage = data?.data.homepage! <- error here
const brands = homepage?.brands[0]!
const header = homepage?.header!
const footer = homepage?.footer!
const video = homepage?.video!
useQuery.tsx
import type { Query } from '@gql/graphql'
type Props = {
data: Query
}
const useQuery = async (query: string) => {
const response = await fetch('https://graphql.datocms.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: Bearer ${import.meta.env.DATOCMS_API_TOKEN},
},
body: JSON.stringify({ query: query }),
})
const data: Props = await response.json()
return { data }
}
export default useQuery
`