Fail to load the image - javascript

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

Related

How to handle new tabs with the page object model with Playwright

I want to know how to handle a tab or multiple tabs when using Page object model.
My test runs successfully if i don't use the page object model function to run it.
Basically when i click and navigate to the new tab i am using this on the normal test without the POM:
const [newPage] = await Promise.all([
page.waitForEvent('popup'),
page.locator(button...).click();
]);
and then using the newPage as my new tab and it's working.
await newPage.locator(field).fill(testing);
...SNIP..
When using the POM I cant do that and I am not able to continue with the rest of the test, it doesnt recognise the new tab as i cant declare the new page in the POM.
Can someone point me in the right direction ?
How can i implement the same logic using the POM ?
Thanks
Maybe this will help. I also puzzled over how to do it.
constructor(page) {
this.page = page;
this.wait_for_event = page.waitForEvent('popup');
this.your_button = page.locator(button...);
}
async f(){
const [newPage] = await Promise.all([
this.wait_for_event,
this.your_button.click(),
]);
await newPage.getByPlaceholder or another method('placeholder text').fill('');
}
In my case something like this works:
import { test } from '#playwright/test';
import { LoginPage } from '../../pages/LoginPage';
import { ProductsPage } from '../../pages/ProductsPage';
const purchasedProduct = 'Sauce Labs Backpack';
test.beforeEach(async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goTo('inventory.html');
});
test('As a user I want to open a new tab and visit it', async ({
page,
context,
}) => {
const productsPage = new ProductsPage(page);
const [newPage] = await Promise.all([
context.waitForEvent('page'),
productsPage.openNewTabWithProduct(purchasedProduct),
]);
await newPage.locator('text=Sauce Labs Onesie').click();
});
The crucial part is you have to put "context" instead of page as your test attribute. Then just use your newly created page

Youtube playlist thumbnail image not working in Next Js

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

NextJS Router doesn't reload data until page refocus

Currently working with NextJS, but struggling to make an indexing page of sorts. With the router, I'm trying to get the page number by doing this:
let router = useRouter()
let page = isNaN(router.query.page) ? 1 : parseInt(router.query.page);
So that when I go to page=1, page=2 etc, I get new sets of data.
The functionality for this is called in the same main component, and is a React Query function:
const {data, status} = useQuery(["keycaps", {manu: manuId}, {prof: profileId}, {col: colorId}, {stat: statusId}], getKeycaps)
And said function looks like this:
const getKeycaps = async(key) => {
const manuId = key.queryKey[1].manu
const profileIds = key.queryKey[2].prof.map(id => `profile.id=${id}`)
const colorIds = key.queryKey[3].col.map(id => `filter_colors.id=${id}`)
const statId = key.queryKey[4].stat
const profileQueryString = profileIds.join("&")
const colorQueryString = colorIds.join("&")
let urlParams = new URLSearchParams(document.location.search);
let page = urlParams.get("page") == null ? 1 : parseInt(urlParams.get("page"));
let start = (page * 10) - 10
const data = await axios(`
${process.env.REACT_APP_STRAPI_API}/keycaps?${manuId ? 'manufacturer.id=' + manuId + '&' : ''}${profileQueryString ? profileQueryString + '&' : ''}${colorQueryString ? colorQueryString + '&' : ''}_start=${start}&_limit=10`)
return data.data
}
When initially loading pages, like directly pasting the url of the index in (i.e. keycaps?page=2), it will get all the results all fine. However, if I start using navigational buttons like this:
<Link href={`/keycaps?page=${page - 1}`}> // next/link
<div className="w-32 rounded-lg cursor-pointer">
Prev
</div>
</Link>
<Link href={`/keycaps?page=${page + 1}`}>
<div className="w-32 rounded-lg cursor-pointer">
Next
</div>
</Link>
The whole thing starts to break down. Essentially, the page doesn't actually reload any data or results until the page is unfocused. So, if I press the Next button to go to the next page, it won't load the data until I do something like tab to a new window or check a different internet tab, and then when I come back, the data will all magically load within a second.
I've tried this with next build && next start too, and this produces the same results. I just want to get the page results when the next and prev page buttons are pressed, and in a way that doesn't require the user to switch tabs to get content.
I will note that I do have a getStaticProps on this as well. It does the following:
export async function getStaticProps() {
const allKeycaps = (await getAllKeycaps() || 'Error')
return {
props: { allKeycaps }
}
}
Which will call an api script, and said script does this:
async function fetchAPI(query, {variables} = {}) {
const res = await fetch(`${process.env.REACT_APP_STRAPI_API}/graphql`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
variables,
}),
})
const json = await res.json()
if (json.errors) {
console.error(json.errors)
throw new Error('Failed to fetch API')
}
console.log('json', json.data, variables)
return json.data
}
/* Keycap related grabs */
export async function getAllKeycaps() {
const data = await fetchAPI(
`
{
keycaps {
id
slug
name
published_at
updatedAt
profile {
id
name
}
manufacturer {
id
name
lead
}
status {
id
name
}
colors
filter_colors {
color
}
kits
designer
thumb {
formats
}
}
}
`
)
return data
}
Anyone know how to get this to work? To navigate between indexes like this? I've been trying to look for Next tutorials that use navigations like page 1, page 2 etc but all I can find is examples of blog articles with slugs, no index searches of any kind.
Thanks a lot in advance.
Answer found:
When setting data and status using useQuery
const curPage = router.query.page == null ? 1 : router.query.page
const {data, status} = useQuery(["keycaps", {manu: manuId}, {prof: profileId}, {col: colorId}, {stat: statusId}, {page: curPage}], getKeycaps)
And then, in getKeycaps
const page = key.queryKey[5].page
I guess the "urlParams" approach wasn't a good one? Or at least, not one that was updating quick enough. So passing through the router page number seems to work better.

Getting results of a MongoDB query to use in a select menu

I'm working on a website that allows you to search for people in a database based on location. Initially, the dropdown menu (select) is populated with provinces that available people are in. I'm trying to use a mongo query to populate that select menu. But when I try to get the values outside the function, it does not work and the select menu turns up empty.
import * as React from "react";
import axios from "axios";
const Locations = () => {
let options = null;
function axiosTest() {
// This is a server link i created that runs a query that returns distinct provinces from the database
const promise = axios.get("/api/v2/people/provinces");
const dataPromise = promise.then(result => result.data).then(data => {console.log(data);return data;});
// The console.log() above displays all the objects that are in the query given by the server link in an array
// e.g. ['British Columbia', 'Alberta', 'Saskatchewan', etc.]
}
var type = axiosTest();
console.log(type); // now it displays it as "undefined"
if (type) {
options = type.map((el) => <option key={el}>{el}</option>);
}
return (
<div
style={{
padding: "16px",
margin: "16px",
}}
>
<form>
<div>
<select>
{
/** This is where we have used our options variable */
options
// and the select menu is shown as blank, because it doesn't have any options to fill it with
}
</select>
</div>
</form>
</div>
);
};
export default Locations;
Can someone please help me get this to work? Is it something to do with Threads and Concurrency? I'm unfortunately rusty at that.
Function axiosTest() does not return anything. You should specify change your code so the function would return the result of DB query. You can also change .then() syntax with async/await so your code would become more readable.
const Locations = async () => {
let options = null;
function axiosTest() {
return axios.get("/api/v2/people/provinces");
}
var type = await axiosTest();
console.log(type);
...
};

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

Categories