I am getting a syntax error in my React return
Syntax error: Unexpected token, expected ","
If I remove
{data.nodes && data.nodes.map((node) => (
{node.title}
))}
I get a different error BUT I do see all my JSON data in my terminal, so I know it is getting pulled. I am having trouble looping/mapping through it within my return
the error if I remove map…
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
So my logic is to render the data as JSX and then pass it along from GetSlides to Page. You will see the {page} getting passed as well, but that works fine
async function GetSlides() {
const data = await getHomeSlides()
console.log(data)
if (!data) return null;
return (
<div>
<h1>Slides</h1>
{data.nodes && data.nodes.map((node) => (
{node.title}
))}
</div>
)
}
export default function Page( {page} ) {
return (
<>
<Layout>
<Head>
<title>{ page.seo.title }</title>
<meta name="description" content={page.seo.metaDesc} />
</Head>
<Header />
<ContainerFull>
<h1>{ page.title }</h1>
<GetSlides />
<div dangerouslySetInnerHTML={{ __html: page.content }} />
</ContainerFull>
</Layout>
</>
)
}
This is the query
const API_URL = process.env.WORDPRESS_API_URL
async function fetchAPI(query, { variables } = {}) {
const headers = { 'Content-Type': 'application/json' }
if (process.env.WORDPRESS_AUTH_REFRESH_TOKEN) {
headers[
'Authorization'
] = `Bearer ${process.env.WORDPRESS_AUTH_REFRESH_TOKEN}`
}
const res = await fetch(API_URL, {
method: 'POST',
headers,
body: JSON.stringify({
query,
variables,
}),
})
const json = await res.json()
if (json.errors) {
console.error(json.errors)
throw new Error('Failed to fetch API')
}
return json.data
}
export async function getHomeSlides() {
const data = await fetchAPI(`
{
artwork {
nodes {
artwork {
available
description
medium
price
size
arttypedisplay
homePageSlideshow
}
title
uri
slug
seo {
metaDesc
title
}
}
}
}
`)
return data?.artwork
}
2
Answers
Thank you to Drew Reese for the great insight..
the final code invloved putting both queries into getStaticProps
You tried to make your
GetSlides
componentasync
. React doesn’t work like that, the render function is 100% synchronous and should be free of side-effects. Do the data fetching in anuseEffect
hook and store result in local component state. An asynchronous function is declared inside the effect callback since react hooks are also synchronous.