Youtube playlist thumbnail image not working in Next Js - javascript

In my next js app I'm fetching YouTube playlist and assigning them dynamic card. but when I use map the url doesn't work but in plain omg tag it works fine.
the code is as follows.
index.js
function Home({result}) {
return (
<...
<ShowsView result={result}/>
.../>
)
} export default Home;
export async function getStaticProps(){
const MY_PLAYLIST = process.env.YOUTUBE_PLAYLIST_ID;
const API_KEY = process.env.YOUTUBE_API_KEY;
const REQUEST_URL = `https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${MY_PLAYLIST}&key=${API_KEY}`;
const response = await fetch(REQUEST_URL);
const result = await response.json();
return{
props:{result: result},
revalidate: 3600,
}
}
In my index file executing result.items[0].snippet.thumbnails.maxres.url will return a url for the image. the issue is when I map it through the url doesn't work.
{result.items.map((res, idx)=>{
//console.log(res.snippet.thumbnails.maxres);
//console.log(res);
//console.log(result);
return (
//<ShowCard result={result.items[idx].snippet.thumbnails.maxres.url} key={idx}/>
<ShowCard result={res.snippet.thumbnails.maxres.url} key={idx}/>
);
})}
using like this it return every data until I get to the thumbnails. res.snippet.thumbnails.default this works. but res.snippet.thumbnails.default.url throws an error.
TypeError: Cannot read properties of undefined (reading 'url')
This error happened while generating the page. Any console logs will be displayed in the terminal window
The log points after default. What is the mistake here?

Perhaps res is also being accessed during init of the app, which is an empty object.
try doing this:
res.snippet.thumbnails.default?.url

Related

Error when loading json spritesheet in react-pixi

I am using Pixi 6.5.8 and react-pixi, i am trying to load sprite sheet from json file. I am using method i found on codepen examples posted on react-pixi documentation(https://codepen.io/inlet/pen/VwLLYme).
Json was generated from TexturePacker, with output specified for PIXI, so i guess this is not a problem, the same sprite sheet worked perfectly when i used it in Pixi v7 and Assets.load method, however i am forced to work with react now).
Thats the code
export default function JetFighter() {
const [frames, setFrames] = React.useState([]);
const app = useApp();
const spritesheet = "./assets/Sprites/ship_2_idle-0.json";
React.useEffect(() => {
app.loader.add(spritesheet).load((_, resource) => {
setFrames(
Object.keys(resource[spritesheet].data.frames).map((frame) =>
PIXI.Texture.from(frame)
)
);
});
}, []);
if (frames.length === 0) {
return null;
}
return (
<Container x={250} y={250}>
<AnimatedSprite
animationSpeed={0.5}
isPlaying={true}
textures={frames}
anchor={0.5}
/>
</Container>
);
}
Error
I've tried to use Assets.load from "#pixi/assets":^6.5.8", but with this method i am getting such error:
Error from Assets.load method
Do you have any idea how to solve this issue?

How to connect loop data to pdfgeneratorapi with wix corvid?

I'm generating PDF by using https://pdfgeneratorapi.com/.
Now I can show data one by one using this code.Can any one give me suggestion how can show all data with loop or any other way?
This below photos showing my template from pdfgenerator .
This is the code I'm using to generate PDF
let communicationWay1=[
{0:"dim"},
{1:"kal"}
];
let cstomerExpence1=[
{0:"dim"},
{1:"kal"}
];
let title="test";
let names="test";
let phone="test";
let email="test";
let maritalStatus="test";
let city="test";
let other="test";
const result = await wixData.query(collection)
.eq('main_user_email', $w('#mainE').text)
.find()
.then( (results) => {
if (results.totalCount>0) {
count=1;
// title=results.items[1].title;
names=results.items[0].names;
email=results.items[0].emial;
phone=results.items[0].phone;
maritalStatus=results.items[0].maritalStatus;
city=results.items[0].city;
other=results.items[0].cousterExpenses_other;
title=results.items[0].title;
communicationWay=results.items[0].communicationWay;
cstomerExpence=results.items[0].cstomerExpence;
}
if (results.totalCount>1) {
names1=results.items[1].names;
email1=results.items[1].emial;
phone1=results.items[1].phone;
maritalStatus1=results.items[1].maritalStatus;
city1=results.items[1].city;
other1=results.items[1].cousterExpenses_other;
title1=results.items[1].title;
communicationWay1=results.items[1].communicationWay;
cstomerExpence1=results.items[1].cstomerExpence;
}
} )
.catch( (err) => {
console.log(err);
} );
// Add your code for this event here:
const pdfUrl = await getPdfUrl
({title,names,email,phone,city,maritalStatus,other,communicationWay,cstomerExpence,title1,
names1,email1,phone1,city1,maritalStatus1,other1,communicationWay1,cstomerExpence1
});
if (count===0) { $w("#text21").show();}
else{ $w("#downloadButton").link=wixLocation.to(pdfUrl);}
BELOW CODE IS BACKEND CODE/JSW CODE.
Also I want to open pdf in new tab. I know "_blank" method can be used to open a new tab.But I'm not sure how to add it with the url
import PDFGeneratorAPI from 'pdf-generator-api'
const apiKey = 'MYKEY';
const apiSecret = 'MYAPISECRET';
const baseUrl = 'https://us1.pdfgeneratorapi.com/api/v3/';
const workspace = "HELLO#gmail.com";
const templateID = "MYTEMPLATEID";
let Client = new PDFGeneratorAPI(apiKey, apiSecret)
Client.setBaseUrl(baseUrl)
Client.setWorkspace(workspace)
export async function getPdfUrl(data) {
const {response} = await Client.output(templateID, data, undefined, undefined, {output: 'url'})
return response
}
Just put it in a while loop with a boolean condition.
You can create a variable, for example allShowed, and set its value to False. After that, create another variable, for example numberOfDataToShow, and set it as the number of elements you want to display. Then create a counter, countShowed, initialized with 0 as its value.
Now create a while loop: while allShowed value is False, you loop (and add data).
Everytime a piece of your data is showed, you increment the value of countShowed (and set it to go on adding/showing data). When countShowed will have the exact same value of numberOfDataToShow, set allShowed to True. The loop will interrupt and all your data will be showed.
You would need to use the Container or Table component in PDF Generator API to iterate over a list of items. As #JustCallMeA said you need to send an array of items. PDF Generator API now has an official Wix Velo (previously Corvid) tutorial with a demo page: https://support.pdfgeneratorapi.com/en/article/how-to-integrate-with-wix-velo-13s8135

Passing Puppeteer page as params in a function is not working as expected

Intro
The loginLinkedin takes me to the login page and then return for me the puppeteer page which is then assigned to root so I can still have more options do work with it.
const root = await loginToLInkined("https://www.linkedin.com/login");
await root.goto(url);
max_page = await getMaxPage(root);
console.log("max page",max_page)
I then goto(url)
url is another page I need to go to.
after that I call the getMaxPage(root) with root as a param so I can evaluate() in that function
Problem
const getMaxPage = async root => {
const maxPage = await root.evaluate(()=> {
return document.querySelector(
"li.artdeco-pagination__indicator:nth-last-Child(1)"
);
});
console.log(maxPage)
return parseInt(maxPage.innerText);
};
The problem is that when I console.log(maxPage) it returns undefined and I realized that adding a root s a param isn't actually working the way I'm supposed to do.
What am I doing wrong and how it properly done.
Note I have actually tried to root.evaluate without adding a function and adding the root as a param and it actually returned for me the maxpage
The issue is in what you return from page.evaluate():
const maxPage = await root.evaluate(()=> {
return document.querySelector(
"li.artdeco-pagination__indicator:nth-last-Child(1)"
);
});
This is a DOM node, which is a complex object that cannot be serialized, and the return value must be serializable in order to be returned back to node from Chromium.
So to fix that and all the future scripts just return only what is needed and what can be JSON.stringifyed without error. As pguardiario correctly noted in the comment, in this case it's enough to return innerText from that node:
const maxPage = await root.evaluate(()=> {
return document.querySelector("li.artdeco-pagination__indicator:nth-last-Child(1)").innerText;
});

Fail to load the image

Error from the Browser console:
https://static.food2fork.com/pastaallavodkaa870.jpg.jpg 404
Trying to display the image on the browser, I don't know if it is a problem from my code or food2fork end.
My index.js:
// always make sure you have the right directory
// import field
import Search from './models/Search';
// import all the function from the view
import * as searchView from './views/searchView'
import {elements} from './views/base';
/* Global state of the app
- Search obj
- current recipe obj
- shopping list object
- liked recipes
*/
// everytime we reload the app, it will be empty
const state = {}
const controlSearch = async () =>{
// 1) Get the query from the view
const query = searchView.getInput();
if(query){
// 2) new search object and add it to state
state.search = new Search(query); // new instance of the search class
// 3) prepare UI for results
// 4) Search for recipes
await state.search.getResults(); // await this promise then render the result
// 5) render result in the UI, reminder u got hit the search button
searchView.renderResult(state.search.result);
}
}
elements.searchForm.addEventListener('submit', e => {
e.preventDefault();
controlSearch();
});
My Search.js:
// this is the external source simply call its name
import axios from 'axios';
// query and then the search result
// class declarition ES6
export default class Search {
constructor(query){
this.query = query;
}
async getResults(){
// fetch is only gonna work for modern browser
// HTTP request axios
// if you enter the invalid the key it will not work
//key is blurred out for stackoverflow
const key = '------------------------';
// return json
// if we can not access it we are going to use the cors proxy
// const proxy = you can use google to search for cors proxy
try{
const res = await axios(`https://www.food2fork.com/api/search?key=${key}&q=${this.query}`);
this.result = res.data.recipes;
// console.log(this.result);
} catch(error){
alert(error);
}
}
}
My searchView.js:
// if we are in the current folder then it is simply base
import {elements} from './base';
// return the input value from the field
// implicit search automatically return
export const getInput =() => elements.searchInput.value;
const renderRecipe = recipe =>{
const markup = `
<li>
<a class="results__link" href="#${recipe.recipe_id}">
<figure class="results__fig">
<img src="${recipe.image_url}.jpg" alt=${recipe.title}>
</figure>
<div class="results__data">
<h4 class="results__name">${recipe.title}</h4>
<p class="results__author">${recipe.publisher}</p>
</div>
</a>
</li>
`;
// insert the html
elements.searchResList.insertAdjacentHTML('beforeend',markup);
}
export const renderResult = recipes => {
recipes.forEach(renderRecipe);
}
My base.js:
// all the DOM element will be in this class object
export const elements = {
searchForm: document.querySelector('.search'),
searchInput: document.querySelector('.search__field'),
searchResList: document.querySelector('.results__list')
}
I am new to the web-Dev and learning by myself. I hope this is not a bad question. I need a experienced mind to help me take a look at this error, since it is not a syntax or logic error. Thanks a lot and have a great day.
https://static.food2fork.com/pastaallavodkaa870.jpg.jpg
Did you mean to add .jpg.jpg?.. if not then take off the last .jpg
https://static.food2fork.com/pastaallavodkaa870.jpg
Remove the duplicate .jpg and it will work.
https://static.food2fork.com/pastaallavodkaa870.jpg

React native cannot read property '0' of undefine

I'm new with ReactJS and today I have encountered a few problems.
I am currently using Redux to store my data and I was able to retrieve all the data from the props.
Ie.
const { recipe, loadingRDetail } = this.props;
console.log(recipe.macros);
recipe macros will show me 5 values in array.
Array Image Console Log
But when I tried to accessed to the array, It will throw me an error "Cannot read property '0' of undefined".
I have tried
console.log(recipe.macros[0])
and
const {macros} = recipe;
macros.map((i) => {
....
}...
I have no luck with both of these
This is the error I get
Red Warning error
Actually, it's just because your macros data is asynchronously loaded so you have to add a test to check if it's loaded.
You can try this:
const {macros} = recipe;
if (macros && macros.length) {
macros.map((i) => {
....
}...
}
Or if you already are in your Render method you can just try this :
const {macros} = recipe;
return (
{
macros && macros.length && /* It will check if macros has elements inside */
macros.map((i) => {
....
}...
}
}
)

Categories