How to get data from GraphQL CMS - javascript

I am trying to follow this tutorial.
I am stuck at 1:02.
Ania is able to generate the thumbnails, but I get an error that says:
TypeError: Cannot read properties of undefined (reading 'thumbnail')
It points to the image tag on the index.js page.
I tried to clear the error that is generated because Next.js wants to use its Image tag instead of img src - but the error still appears. The image block now looks as follows:
I get the same error when I comment the thumbnail line and just try to use title.
I can't make sense of the advice generated when I google this error - such as the note in this post, which I think is suggesting that the code is trying to run before the graphql connection has been made and loaded, for it to be able to retrieve the data. If that understanding is correct, then I think I need to put await somewhere to ask for graphql to load before the results are returned, but I don't know how to do that.
I'm not sure that I've understood the error or advice on how to resolve it correctly.
I have also seen this post, which suggests that problems could be because there are components in the pages folder that are not pages. Is it possible that the [slug].js file being in the pages folder is a source of the problem? If so, where can I move it to solve for that (and why didn't Ania have to do this)?
When I try to console.log randomVideo(videos) beneath the definition of that const (above the return statement), I get two instances of undefined. When I try to console log (randomVideo(videos)).title}, I get the same form of error as posted in the title.
I tried not using the randomVideo const in the return statement, so that the Image tag has:
> <Image
> src={videos.videos[0].thumbnail.url}
> width={400}
> height={400}
> alt={videos.videos[0].title}
> />
When I try this, I get an error that says:
Error: Invalid src prop
(https://media.graphassets.com/NLX6ICjoR5Wt6zYOoLYO) on next/image,
hostname "media.graphassets.com" is not configured under images in
your next.config.js See more info:
https://nextjs.org/docs/messages/next-image-unconfigured-host
I tried amending the next.config.js to the following, but I still get the same error:
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = {
nextConfig,
images: {
domains: ['assets.example.com'],
},
}
For reference, videos is defined as follows:
const data = await graphQLClient.request(videosQuery)
const videos = data.videos
return {
props: {
videos
}
}
I don't understand why the error messages are different, when I use a different means of getting a video in the return statement.
I have tried console logging all versions of randomVideo inside and outside the return statement, but keep getting undefined.
I've run out of things to try to try and get data in the app.

Related

Why can't I access useAsyncData in a Nuxt 3 script setup tag for an if-statement?

I'm using the Prismic API to get some data that I want to show in my Nuxt3 template.
Everything works fine, I just want to show a 404 page when there is no data instead of a 500 error. I have added a check if the data is empty:
<script setup>
const route = useRoute()
const name = route.params.werke;
const { client } = usePrismic()
const { data: werk } = await useAsyncData('werk', () => client.getByUID("werk", name))
if (!werk.uid) {
throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })
}
</script>
The problem is, that at the if (!werk.uid) part werk.uid is ALWAYS empty. So I always get that 404 error. In my template werk.uid is not empty so I assume there is a problem, where the if statement can't access the const variable with useAsyncData?
Any ideas? The official Docs recommend it in a similar way to me: https://v3.nuxtjs.org/getting-started/error-handling/#example-1
Someone in the prismic forum helped me to find the solution. It is a Vue 3 specific problem:
You'll need to use .value after werk: (!werk.value). Instead of just (werk.anything)

PowerBI Embedded API: "too few fields" error when trying to export data

I'm using the Power Bi Embedded API to show reports to my users in a web application.
The API has an exportData() method that is designed to export either the full data or the summarized data from a visual in the report.
My problem occurs when trying to export the summarized data:
myVisual.exportData(ExportDataType.Summarized);
when I do this, this is what I get back:
As you can see, the returned data has a TooFewFields error, with the message Too few fields: expected 3 fields but parsed 1.
Can anyone explain what this error means, and why it is happening? I tried googling, but didn't find anything regarding this particular error.
Note that:
Exporting the full data, instead of the summarized one, works
correctly
Exporting the summarized data from the UI (by clicking
export data in the top right corner of the visual) works correctly
This seems to happen on all visuals in the report
The "TooFewFields" error occurred because, The ‘exportData()’ method mainly consists of 2 parameters Namely Summarized Datatype and Count of Rows to be returned.
But the code that you have written does not consist the parameter as expected. You have to include Models. Exportdatatype. Summarized and the row count to get the required result.
Find the below code snippet:
1.Get the page which contains visual:
const pages = await report. getPages();
let page = pages.filter(function (page) {
return page.isActive
})[0];
const visuals = await page.getVisuals();
2 Find the target visual:
let visual = visuals.filter(function (visual) {
return visual.name === "Required_Visual_Name";
})[0];
3.Export data from visual:
const result = await visual.exportData(models.ExportDataType.Summarized,100);
console.log(result.data);
Output:
Please find the reference here for exporting summarized data:
https://learn.microsoft.com/javascript/api/overview/powerbi/export-data

Error with my server file - Invalid URL: index.js

I am getting the following error when trying to run my server (index.js):
Error: TypeError [ERR_INVALID_URL]: Invalid URL: index.js
The code block is here:
app.get('/:url', async function (req, res) {
try {
return res.status(200).json(data);
} catch (ex) {
console.log(ex);
return res.status(500).json({ message : "Oops." });
}
With the specific line of code it is referring to is:
const site = await .open(decodeURIComponent(req.params.url));
Has anyone ever encountered this error before, and have any idea how to fix it in this context? Not sure how it is throwing an error for my entire index.js server
Note: This is an express app
The value of req.params.url is index.js.
A web browser can expand index.js into an absolute URL because it knows that it can use the URL of the current HTML document as the base URL.
You're running your code in Node.js. It doesn't run inside a document. There is no base URL.
You need to provide an absolute URL (e.g. http://example.com/index.js) yourself.
That said, I suspect wappalyzer may require that you give it the URL to an HTML document not a JS file.
Well, since there isn't much that i can see about your usage, I'm just going to assume you went to something like http://localhost/index.js.
The problem now is, that wappalyzer does not actually get a valid url. It gets index.js without any form of protocol (http/https/ws/wss...). This means it doesn't know what to do and tells you that the url you provided is invalid.
In order to fix this go to http://localhost/https%3A%2F%2Flocalhost%2Findex.js or append https:// or something similar to your parameter.

NextJS Dynamic Routing - Is it possible to set array of route names?

I'm using dynamic routing in my app. Here is the folder structure I'm working with
-pages
-department
-[slug].js
Now I want to show the page if only the slug value is cse, eee, swe, english e.t.c otherwise I want to show the 404 Not Found page. Is there any way to set the array of route names ? Then, if slug value(which I can get using getServerSideProps) is included in that array, I will serve the page otherwise serve the 404 Not Found page.
Why I need that ?
In getServerSideProps function, I'm getting data from api end-point. In this case if slug value is not included in the api-endpoint, server throws Request failed with status code 501 error!
So if slug value is cse, the api-endpoint is available and I can get the data. If slug value is anything or xyasdfs, the api-endpoint is not available and I can't get the data and the server throws the following error.
i would check in my component for a property in my response body.. like, if all the departments have a name,, then check for it, if it doesn't exist, then return a 404.
It should be something like this to render from server side
Page.getInitialProps = async ({query}) => {
if(query.slug == 'cse') {
//codes
}
}
or you can use next Router hook
https://nextjs.org/docs/routing/dynamic-routes

WP REST API ERROR 401 While trying to fetch image from wp:featuredmedia

I'm trying to fetch featured image from my published post but it seems impossible! I get
an error :( that's the code:
function fetchSlideShow(){
let endpoint = "http://loreleiheckmann.com/wordpress/wordpress/wp-json/wp/v2/Vinyls?_embed";
fetch(endpoint)
.then(e => e.json())
.then(showSlideShow);
}
function showSlideShow(data){
console.log(data);
data.forEach(showSingleSlide);
showSlides();
}
function showSingleSlide(aSlide) {
let template = document.querySelector(".slide_template").content;
let clone = template.cloneNode(true);
console.log(aSlide);
clone.querySelector("img").setAttribute("src", aSlide._embedded["wp:featuredmedia"]
[0].media_details.source_url);
let SlideList = document.querySelector("#SlideList");
SlideList.appendChild(clone);
}
While going to the array I see error 401 :( and moreover: Cannot read property 'source_url' of undefined" I don't know what I'm doing wrong .. any insights?
HERE ARE THE ERRORS -> 401 ON CONSOLE + PROBLEM WITH URL.:
Please try changing your url in the endpoint variable:
let endpoint = "http://loreleiheckmann.com/wordpress/wordpress/wp-json/wp/v2/posts?per_page=20&_embed=wp:featuredmedia
If you need more data you can add them with a comma:
wp-json/wp/v2/posts?per_page=20&_embed=wp:term,wp:featuredmedia
Post per page is optional, but I would prefer having that set.
And you should write what image size you need. That way rest api will give you the right source url:
_embedded['wp:featuredmedia']['0'].media_details.sizes.medium_large.source_url
I think it would also be better practice if you use an ssl certificate, there are free by "Let's encrypt".
EDIT:
Your screenshot shows the rest api message:
wp:featuredmedia: Array(1)
0:
code: "rest_forbidden"
data: {status: 401}
message: "Sorry, you are not allowed to do that."
So the 401 status code means: unauthorised
Seems like you are not allowed to access the data via rest api.
There could be multiple reasons for that:
The image is attached to an unpublished post. The post may have the status "private" or "draft", and therefore is not public available.
Your post (and attached image) is not available for not logged in users. If there is a restriction to view your code, this also applies to rest api.
Maybe you are using some kind of membership plugin that restricts the wp rest-api. Try deactivating all plugins if one of them affects the behaviour.
You have added some custom code to restrict access rest api access.
If nothing works for you, you should look into your database and check the medias post_status.
I think it is working fine, but you do not have access to view the posts data. This is what the 401 error indicates.
To whom it may concern - In the end, I added image in WP by custom post type ( I gave up wp:featured media - I wasn't able to fetch it.) Afterward I added a code to JS -> b.querySelector(".img").setAttribute("src", a.acf.image.url); so it works:)

Categories