I want to wrap the firebase image path in v-for - firebase

I'm not a developer, so the question might look stupid. I ask for your understanding.
There is an existing code with v-for
v-tab-item(
v-for="(item, index) in getCharacterSkinList"
:key="index"
)
v-img(:src="require('~/static/img/skin/' + item.id + '_' + getSkinId + getSkinState + '.webp')"
Current Changes
v-tab-item(
v-for="(item, index) in getCharacterSkinList"
:key="index"
)
img(:src="imageSrc")
export default {
mounted() {
const skinId = this.$store.getters['skin/getSkinId']
const state = this.$store.getters['skin/getSkinState']
const storageRef = this.$fire.storage.ref()
this.getCharacterSkinList.forEach((item, index) => {
const imageRef = storageRef.child(
`skin/${item.id}_${skinId}${state}.webp`
)
imageRef
.getDownloadURL()
.then((url) => {
this.$set(this.imageSrc, index, url)
})
.catch((error) => {
console.log(error, imageSrc)
})
})
this.$store.dispatch('skin/asyncCharacterSkin')
},
}
in this case, getters works successfully.
but failed to load item.id.
I tried
v-img(:src="getImageSrc(item.id)")
methods: {
getImageSrc(id) {
const skinId = this.$store.getters['skin/getSkinId']
const state = this.$store.getters['skin/getSkinState']
const storageRef = this.$fire.storage.ref()
const imageRef = storageRef.child(`skin/${id}_${skinId}${state}.webp`)
return imageRef.getDownloadURL()
},
}
I tried to change it to method, but it did not work because returned prosmised.
What other ways can I try?

getDownloadURL() is an asynchronous method so you should declare your method as async and use await, as follows (untested):
async getImageSrc(id) {
const skinId = this.$store.getters['skin/getSkinId']
const state = this.$store.getters['skin/getSkinState']
const storageRef = this.$fire.storage.ref()
const imageRef = storageRef.child(`skin/${id}_${skinId}${state}.webp`)
const downloadURL = await imageRef.getDownloadURL();
return downloadURL;
},

Related

Displaying data from SWAPI

I am trying to display film details from this API https://swapi.dev/api/films in NextJS but I keep getting an error. It has something to do with the getStaticPath function. I am using this code: any help welcome.
import fetch from 'isomorphic-unfetch';
export const getStaticPaths = async () => {
const res = await fetch('https://swapi.dev/api/films');
const data = await res.json();
console.log("This is " + JSON.stringify(data));
const paths = data.results.map(film => {
return {
params: { id: film.episode_id.toString() },
};
});
return {
paths,
fallback: false,
};
};
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch(`https://swapi.dev/api/films` + id);
const data = await res.json();
return {
props: { film: data },
};
};
const Details = ({ film }) => {
return (
<div>
<h1>Episode {film.episode_id}</h1>
<h1>{film.title}</h1>
</div>
);
};
export default Details;
I am expecting the episode ID and title to display
enter image description here
I have tried taking 'results' out of 'data.results.map', so 'data.map' but just results in a error says data.map is not a function...I guess because data is an object not an array. But results is an array so I am still lost. I do think the issue lies here somewhere though...

React Query with firebase returns undefined

I am very new to state management libraries and the one that I chose was React Query. I have followed multiple tutorials about it with mock data, but when I try to use my firebase imported data, it returns undefined. I am attaching all of my code with instances of React Query in it. This app is in next js 12.
file where I want to fetch and render data
const fetchDbData = async () => {
const {currentUser} = UseAuth();
function getLoc() {
if (currentUser) {
return 'users/' + currentUser.uid + '/userInvestments'
} else {
return 'users/TestDocumentForDatabase/userInvestments'
};
}
const loc = getLoc();
const q = query(collection(db, loc));
const snapshot = await getDocs(q);
console.log(snapshot)
const {data, status, error} = useQuery(
['firebaseData'],
() => snapshot.forEach(doc => doc.data()),
{
refetchOnWindowFocus: false
},
{
retry: false
},
)
return {data, status, error}
}
export default function usePortfolio() {
const {data, status, error} = fetchDbData
.....
_app.js
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
useInfiniteQury: false,
},
}
})
export default function App({ Component, pageProps }) {
return (
<QueryClientProvider client={queryClient}>
<AuthProvider >
<RootLayout>
<Component {...pageProps} />
</RootLayout>
</AuthProvider>
</QueryClientProvider>
)}

How to use Promise.all and Promise.allSettled Inisde Getserverside or GetStaticProps

i have component use GetStaticProps like this
export const getStaticProps: GetStaticProps = async () => {
const landingPage = await axios.get(
'https://someapi/'
);
const gameData = await axios.get(
'https://someapi'
);
return {
props: {
landingPageData: landingPage.data,
gameData: gameData.data,
},
revalidate: 120,
};
};
I try to do like this
const promise1 = axios.get(URL1);
const promise2 = axios.get(URL2);
const promise3 = axios.get(URL3);
Promise.all([promise1, promise2, promise3]).then(function(data) {
console.log(data);
});
But I don't know how send the data into the return props
because of the data inside Promise.All

Update Component after post new item to the Database

I am playing around with Sveltekit and I am struggling a bit..
So my problem is, when I add something to the DB it works, but the new Item does not show in the list until i Refresh the page. My Code looks like:
index.js
import { connectToDatabase } from '$lib/db';
export const post = async ({ request}) => {
const body = await request.json()
console.log(body)
const dbConnection = await connectToDatabase();
const db = dbConnection.db;
const einkaufszettel = db.collection('Einkaufszettel')
await einkaufszettel.insertOne({
name: body.newArticle
});
const einkaufsliste = await einkaufszettel.find().toArray();
return {
status: 200,
body: {
einkaufsliste
}
};
}
export const get = async () => {
const dbConnection = await connectToDatabase();
const db = dbConnection.db;
const einkaufszettel = db.collection('Einkaufszettel')
const einkaufsliste = await einkaufszettel.find().toArray();
console.log(einkaufsliste)
return {
status: 200,
body: {
einkaufsliste,
}
};
}
and the Script of index.svelte
<script>
import Title from '$lib/title.svelte'
export let einkaufsliste = []
let newArticle = ''
const addArticle = async () => {
const res = await fetch('/', {
method: 'POST',
body: JSON.stringify({
newArticle
}),
headers: {
'Content-Type': 'application/json'
}
})
fetchArticles()
}
async function fetchArticles() {
const res = await fetch('/')
console.log(res.body)
}
</script>
In the Network Preview Tab the new Item is already added to the List.
As you can read here, you need to reassign the einkaufsliste after fetching the list of elements from the API.
You can do this in your fetchArticles method, like this:
async function fetchArticles() {
einkaufsliste = await fetch('/')
}

Puppeteer element is console.log'able but return undefined in puppeteer

I'm trying to crawl a webpage that has a h3 tag under an a tag. I'm getting the a tag just fine, but when trying to get the innerText of h3 I'm getting an undefined value.
This is what I'm trying to crawl:
const puppeteer = require('puppeteer');
const pageURL = "https://producthunt.com";
const webScraping = async pageURL => {
const browser = await puppeteer.launch({
headless: false,
arges: ["--no-sandbox"]
});
const page = await browser.newPage();
let dataObj = {};
try {
await page.goto(pageURL, { waitUntil: 'networkidle2' });
const publishedNews = await page.evaluate(() => {
const newsDOM = document.querySelectorAll("main ul li");
let newsList = [];
newsDOM.forEach(linkElement => {
const text = linkElement.querySelector("a").textContent;
const innerText = linkElement.querySelector("a").innerText;
const url = linkElement.querySelector("a").getAttribute('href');
const title = linkElement.querySelector("h3").innerText;
console.log(title);
newsList.push({
title,
text,
url
});
});
return newsList;
});
dataObj = {
amount: publishedNews.length,
publishedNews
};
} catch (e) {
console.log(e);
}
console.log(dataObj);
browser.close();
return dataObj;
};
webScraping(pageURL).catch(console.error);
Console log works great, but puppeteer throws:
Cannot read property 'innerText' of null
It looks like your solution is working just fine, but you're not controlling whether the h3 tag is null or not. Try adding an if statement before accessing the innerText attribute, or use the code I left below.
const puppeteer = require('puppeteer');
const pageURL = "https://producthunt.com";
const webScraping = async pageURL => {
const browser = await puppeteer.launch({
headless: false,
arges: ["--no-sandbox"]
});
const page = await browser.newPage();
let dataObj = {};
try {
await page.goto(pageURL, { waitUntil: 'networkidle2' });
const publishedNews = await page.evaluate(() => {
let newsList = [];
const newsDOM = document.querySelectorAll("main ul li");
newsDOM.forEach(linkElement => {
const aTag = linkElement.querySelector("a");
const text = aTag.textContent;
const innerText = aTag.innerText;
const url = aTag.getAttribute('href');
let title = aTag.querySelector("h3");
// there may be some <a> without an h3, control
// the null pointer exception here, accessing only
// if title is not 'null'.
if (title) title = title.innerText;
console.log(title);
// changed the object structure to add a key for each attr
newsList.push({
title: title,
text: text,
url: url
});
});
return newsList;
});
// changed the object structure to add a key for the array
dataObj = {
amount: publishedNews.length,
list: publishedNews
};
} catch (e) {
console.log(e);
}
console.log({receivedData: dataObj});
browser.close();
return dataObj;
};
webScraping(pageURL).catch(console.error);
Let me know if this fixes your problem!

Resources