GraphQL Requests in Image Loader (Next.js + Headless WordPress)
Unanswered
vTotal posted this in #help-forum
vTotalOP
Hi all,
I've got a little challenge for you all. I'm currently building a Next.js with a Headless WordPress setup. For the purpose of optimising images and making sure we're not loading massive image sizes, I'm looking to see if I can get images by their WordPress ID's and using an image loader to load bring the images in from the ID.
I've currently got this as my image loader setup.
When I console log this out, I get the intended image url. However when the page ends up loading it renders it as
Is there any way that I can resolve this promise and provide the images using an image loader?
I've got a little challenge for you all. I'm currently building a Next.js with a Headless WordPress setup. For the purpose of optimising images and making sure we're not loading massive image sizes, I'm looking to see if I can get images by their WordPress ID's and using an image loader to load bring the images in from the ID.
I've currently got this as my image loader setup.
import { GetData } from "./data";
const GET_IMAGE = `
query getImage($id: ID!) {
mediaItem(id: $id, idType:DATABASE_ID) {
sourceUrl
}
}
`;
export default function wpImageLoader({src, width, quality}) {
if(src.includes('_next') || src.includes('http')) {
return `${src}?width=${width}&quality=${quality || 75}`;
}
const numMatch = src.match(/(\d+)/g);
if(numMatch) {
// get image
const id = numMatch[numMatch.length - 1];
const variables = {id};
return GetData(GET_IMAGE, variables).then((res) => {
console.log(res.mediaItem.sourceUrl);
return `${res.mediaItem.sourceUrl}?width=${width}&quality=${quality || 75}`;
});
}
return `${process.env.NEXT_PUBLIC_WORDPRESS_UPLOADS_URL}${src}?width=${width}&quality=${quality || 75}`;
}
When I console log this out, I get the intended image url. However when the page ends up loading it renders it as
/PAGE_IMAGE_IS_ON/[object Promise]
, which is helpful to nobody.Is there any way that I can resolve this promise and provide the images using an image loader?