#Help Fetching Data With Astro, Undefined Error

1 messages · Page 1 of 1 (latest)

slender jungle
#

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

`

lethal falconBOT
#
Houston Plugins Commands
**Commands**

</help:873835752801320991> commands

**Free Credits**

</help:873835752801320991> credits

**MEE6 AI**

</help:873835752801320991> ai

**Levels**

</help:873835752801320991> levels

slender jungle
#

Help Fetching Data With Astro, Undefined Error