0

I've recently set up a Next.js project along with a headless Wordpress CMS. My posts & pages are using custom Gutenberg blocks to pull content through. I've set up the following plugins on the CMS:

WP GraphQl, WP GraphQL Gutenberg, WPGraphQL for Advanced Custom Fields and ACF Pro.

Within ACF I have set up an 'Image' Block, which has a text field and an image field.

Within my code, I have a query in my lib/api.js file like below (14 is the ID for the current image selected - this will change):

export async function getImageById() {
    const data = await fetchAPI(
      `
      query GetImageDetails($id: Int = 14) {
        mediaItems(where: {id: $id}) {
          nodes {
            mediaItemUrl
            mediaItemId
          }
        }
      }
      `
    )

    return data;
}

My folder structure is as follows.

  • lib
  • components
    • Blocks
    • universalImage.js
  • Pages
    • blog
      • index.js
      • [slug].js
  • Public

If I call the query in my index.js file, it returns info on the media image:

export default function Home({posts, first, imgs}) { 
   console.log(imgs)

   return(
      <div>
         //all my content
      </div>
   )
}

export async function getStaticProps() {
    const images = await getImageById();
    const jsonI = await images;

    return {
        props: {
            imgs: jsonI
        }
    }
}

However if I try to call it in my [slug].js file I get back an empty array

[slug].js code

export default function Post(postData, imgs) {
   console.log(imgs)

   return(
      <div>
         //all my content
      </div>
   )
}

export async function getStaticPaths() {
  const allPosts = await getAllPostsWithSlug();

  return {
    paths: allPosts.edges.map(({node}) => `/blog/${node.slug}`) || [],
    fallback: true
  };
}

export async function getStaticProps({ params }) {
  const data = await getPost(params.slug);
  const imgs = await getImageById();

  return {
    props: {
      postData: data.post,
      imgs
    }
  }
}

I am new to Next.js and React so maybe I'm missing something obvious, however any help would be appreciated as I can't progress much further in the project.

Also if you need any more info please let me know.

FetchAPI function is:

async function fetchAPI(query, { variables } = {}) {
  // Set up some headers to tell the fetch call
  // that this is an application/json type
  const headers = { 'Content-Type': 'application/json' };

  // build out the fetch() call using the API_URL
  // environment variable pulled in at the start
  // Note the merging of the query and variables

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({ query, variables })
  });

  // error handling work
  const json = await res.json();
  if (json.errors) {
    console.log(json.errors);
    console.log('error details', query, variables);
    throw new Error('Failed to fetch API');
  }
  return json.data;
}
Matt
  • 43
  • 6
  • You don't have `imgs` declared in `[slug].js`'s `getStaticProps`, is that a typo? Also, can you show the full code for the `getImageById` function? – juliomalves Feb 19 '22 at 17:50
  • yeah it was a typo. I've updated the function now. Also thats all that is in the getImageById function (repasted below): export async function getImageById() { const data = await fetchAPI( ` query GetImageDetails($id: Int = 14) { mediaItems(where: {id: $id}) { nodes { mediaItemUrl mediaItemId } } } ` ) return data; } When i console log the value from index.js it pulls the info through – Matt Feb 21 '22 at 11:13
  • I've added the fetchAPI function in the question. I know it works as i'm able to pull the info from the query when it is in the index.js file – Matt Feb 23 '22 at 16:58
  • The `Post` component parameters are wrong. All props get passed as an object in the first parameter. The component signature should be: `export default function Post({ postData, imgs }) { ... }` (like you have in `Home`). – juliomalves Feb 23 '22 at 22:33
  • This has resolved the issue, thanks very much. – Matt Feb 25 '22 at 16:00

2 Answers2

1

Issue was that I was missing a set of brackets {}.

export default function Post({ postData, imgs }) { ... }

Thanks to @juliomalves!

ouflak
  • 2,458
  • 10
  • 44
  • 49
Matt
  • 43
  • 6
0

You are using object property-value shorthand and return the key "imgs", but there is no variable with that name. You may try to change the name of the "images" constant to "imgs" or need to use imgs: images in return statement.

...
const images = await getImageById();

return {
  props: {
    postData: data.post,
    imgs: images // or change the name of "images" constant to "imgs"
  }
}
Evren Bal
  • 36
  • 3
  • thanks I hadn't realised I left that part out. Unfortunately it is still returning 'undefined' for the imgs variable – Matt Feb 21 '22 at 11:08