Trouble executing query inside [slug].js file in nextjs while implementing acf

Recently, I've completed a setup of a Next.js project in conjunction with a headless Wordpress CMS. To display content, my posts and pages utilize custom Gutenberg blocks. The following plugins have been integrated into the CMS:

- WP GraphQl

- WP GraphQL Gutenberg

- WPGraphQL for Advanced Custom Fields

- ACF Pro

Within the Advanced Custom Fields (ACF) plugin, an 'Image' Block has been configured with a text field and an image field.

In my codebase, there is a query present in the lib/api.js file as shown below (14 represents the ID for the current image selected, which may vary):

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

    return data;
}

The folder structure is organized as follows:

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

When the query is invoked within the index.js file, it successfully retrieves information about 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, attempting to call the query in the [slug].js file results in an empty array being returned:

Code snippet from [slug].js:

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
    }
  }
}

Being new to Next.js and React, I might be overlooking something obvious. Any assistance would be greatly appreciated as progress on the project is currently stalled. Feel free to request more information if needed.

The FetchAPI function used is as follows:

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;
}

Answer №1

One of the reasons for the error was a missing pair of curly braces {}.

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

Credit goes to @juliomalves!

Answer №2

You have applied object property-value shorthand and are returning the key "imgs", but there is no variable defined with that name. Consider renaming the constant "images" to "imgs" or using imgs: images in the return statement.

...
const images = await getImageById();

return {
  props: {
    postData: data.post,
    imgs: images // alternatively, rename the constant "images" to "imgs"
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamically adding a CSS gradient to an element with JQuery

Check out my HSL color picker on JS Bin I have created a simple HSL color picker that dynamically applies a gradient to a range input type upon DOM ready and changes to update the picker. // Code Update Setup $(".cpick-code-hsl").on('change keyup&ap ...

retrieve the source URL of the track element from an external source

I have a video URL from openload that includes 2 subtitles in VTT format. <track kind="captions" src="https://thumb.oloadcdn.net/subtitle/aaaaaaaaaaa/J8i5nTIAM3w.vtt" srclang="en" label="English" default /> <track kind="captions" src="https://thu ...

Is it possible to use a += operator with attr() and val() functions in JavaScript?

Ever since I switched to jQuery, my development process has significantly sped up. However, there is one task that has become a bit more time-consuming: appending a string to an attribute or value. For instance, if you wanted to add a letter to the value ...

Strategies for extracting special character codes from API data within a React functional component

I have been experimenting with a simple trivia API to improve my understanding of REACT. I have noticed that the question data is returning with special character codes, which is causing issues with react jsx. Can anyone suggest a method to easily convert ...

How can I retrieve the value of a div nested within another div?

Alright, let's talk about a situation where we have a draggable HTML div element: <div id="server" draggable="true" ondragstart="return dragStart(event)">Server</div> and also a target div: <div id="target1" ondragenter="return dragE ...

Creating a unique Angular 2 Custom Pipe tutorial

I've come across various instances of NG2 pipes online and decided to create one myself recently: @Pipe({name: 'planDatePipe'}) export class PlanDatePipe implements PipeTransform { transform(value: string): string { return sessionStor ...

How to manipulate HTML dynamically in React using Apollo to avoid unnecessary component re-renders

Currently, I am using Apollo's useQuery function to retrieve a user and their posts in my project. The posts are displayed in both a summary view and a detailed view, with the detailed view positioned on top of the summary view. The visibility of the ...

What is the best way to display a large texture on a small mesh using Three.js?

Having some trouble rendering a texture on a small plane. Imagine I have a texture generated from HTML and rendered as an image. Now, I want to display it on a small plane in VR space near an instrument. The instrument is tiny compared to other objects but ...

Incorrect Date Format in Wordpress IXR_Date

I've been working on some PHP code and here it is: echo date('m/d/Y h:i:s A T'),"<br>"; $match_date = strtotime(date('m/d/Y h:i:s A T')); echo "match_date= ", $match_date, "<br>"; $test = new IXR_Date($match_date); pr ...

Angular @Input set function not being activated during unit testing

Within my Component @Input('price') set setPrice(price) { this.price = price; this.modifyTotalAmount(); } Unit Testing (component.spec.ts) it('should execute function ', () => { spyOn(fixture.componentInstance, ' ...

Revolutionizing Pagination with Rails 6 and Pagy

Currently, I am in the process of integrating pagy into my Rails 6 application. The basic pagy_nav links are functioning properly; however, due to some instances having a large number of items, I am now attempting to implement the pagy_combo_nav_js feature ...

Express serving Node JS HTML pages

I am currently developing a multiplayer game where a server connects two clients to battle against each other. Everything seems to be working smoothly so far. However, I now have the task of integrating a welcoming page where players can input their userna ...

Tips for hiding a modal when clicking outside of it

function openModal(){ document.getElementById("overlay").style.display='block'; document.getElementById("modal").style.display='block'; } function closeModal(){ document.getElementById("overlay").styl ...

Ways to emphasize a particular <li> element?

Currently, I am delving into the world of React and facing a challenge. I have been trying to solve the issue below: When fetching some JSON data, it appears in this format: [ { "answerOptions": [ "Answer A", "Answer B", ...

I am encountering a problem with my Vuex getter where it is sending an Array with a length of 0, but when expanded in the console,

Currently, I'm utilizing Vuex to interact with a Django API in order to fetch count data. state: { DailyCycleDate: [] }, getters: { DailyCycleDate : state => { console.log('Getter') console.log('Length of Array: &apo ...

Verify the route by clicking before the page is loaded

When using Next.js, how can I perform route validation before it loads? According to the official API documentation, the `routeChangeStart` event is triggered prior to a route change, but it seems that once triggered, canceling the event is problematic. ...

Utilize DOM to attach a button onto an image

I am looking to add buttons onto images using DOM manipulation. Each image will have multiple buttons that, when clicked, will delete the image. I am aiming for a functionality similar to this example - JSFiddle This is the code I have attempted so far: ...

Verify whether the element is capable of being scrolled sideways

Is it possible to add indicators to a div to show users that they can scroll left or right within the content? I need a way to detect if the element can be scrolled to either side, so that I can display the appropriate indicator. For example, when there is ...

What could be causing React to render only the final two elements of my array?

I am currently working on a project where I need to display a series of images from a folder. While I have managed to accomplish this, I am facing an issue where the images are being displayed in rows of 2. Although the implementation is successful, it see ...

Implementing USB trigger for cash drawer in web development

I am wondering about how to use a USB trigger to open a cash drawer (BT-100U). Can someone provide guidance on integrating this into a website? Here is a brief description of the BT-100U Cash Drawer Driver Trigger with USB Interface: This device allows fo ...