I work about a Movie App on The Movie DB API with VueJS but I have a problem; I'm trying to pull the poster_path data from The Movie App and print the picture on the page. The problem is; data is being get, the image is also visible, but when I refresh the page, the data cannot be retrieved. But when I remove or add ( / ) between w500 and ${movie.poster_path} in <img :src="`https://image.tmdb.org/t/p/w500/${movie.poster_path}`" > it's coming back. What should I do since we cannot do this all the time?
<script setup>
import axios from 'axios'
var movies = []
async function getMovies() {
const data = axios.get('https://api.themoviedb.org/3/movie/popular?api_key=**********&language=en-US&page=1')
const result = await data
result.data.results.forEach((movie) => {
movies.push(movie)
})
console.log(movies);
}
async function fetch() {
await this.getMovies()
}
getMovies()
</script>
<template>
<br><br><br><br>
<div class="">
<div class="">
<div class="" v-for="(movie, index) in movies" :key="index">
<div class="">
<img :src="`https://image.tmdb.org/t/p/w500/${movie.poster_path}`" >
</div>
</div>
</div>
</div>
</template>
<style scoped lang="scss">
#import '../public/Home.scss';
</style>
Related
I have a simple Vite+Vue.js project in which I am importing data from headless-cms Wordpress using REST API and JSON. It should take and display titles and content of the posts (including imgs when they occure). I'm stuck because all the data on the page display like HTML, i.e. it contains HTML elements, but of course are JSON. Is there any way to convert it to plain HTML? I've tried filtering it with "replacer" method, but for all elements and situations it would take ages.
Screenshot of how data display on page
My component template:
<template>
<h1>Posts</h1>
<div v-for="post in posts" :key="post.id" class="posts">
<h2> {{ post.title.rendered }} </h2>
<div> {{ post.content.rendered }} </div>
</div>
My script in that component:
<script>
export default {
data() {
return {
posts: [],
message: String,
}
},
mounted() {
fetch('https://my-url-here.com/wp-json/wp/v2/posts')
.then(res => res.json())
.then(data => this.posts = data)
.then(err => console.log(err))
}
}
</script>
Just use v-html
<template>
<h1>Posts</h1>
<div v-for="post in posts" :key="post.id" class="posts">
<h2> {{ post.title.rendered }} </h2>
<div v-html="post.content.rendered"></div>
</div>
I have a file called Data.js where i've exported a list with some objects as below
export const DATA = [
{
'loc':'WEB',
'title':"Bukkit List",
'img':'/img/Projects/Bukkit-List.PNG',
'desc':"Bukkit-List is a easy to use and free task managing webapp, with password protection now!",
'fullDesc':""
},
{
'loc':'WEB',
'title':"SilenxIka-Github",
'img':'/img/Projects/SilenxIkaGithub.PNG',
'desc':"First github website for Project SilenxIka, which is completly made from vanilla HTML/CSS/JS",
'fullDesc':""
}
]
Now i have a page called projects.js where i've imported this list and displayed it's content in HTML as below
import Image from 'next/image';
import Link from 'next/link'
import { DATA } from '../../components/Data'
const WEB_RELATED = []
const PC_EXES = []
for(let i=0;i<DATA.length; i++){
if(DATA[i]['loc'] == 'WEB'){
WEB_RELATED.push(DATA[i])
}
else if(DATA[i]['loc'] == 'EXE'){
PC_EXES.push(DATA[i])
}
}
const WEB = WEB_RELATED.map(item =>
<div className="PROJECTS_Projects">
<div className="PROJECTS_Projects_Image">
<Image
className='PROJECTS_Projects_image'
src={item['img']}
layout='fill'
// objectFit='contain'
/>
</div>
{/* if someone clicks on this link i want them to go to [project].js and send This item to [projcet].js */}
// Link-2
<Link href={'/projects/' + WEB_RELATED.indexOf(item)}>
<a>{item['title']}</a>
</Link>
<p>{item['desc']}</p>
</div>
);
const PC = PC_EXES.map(item =>
<div className="PROJECTS_Projects">
<div className="PROJECTS_Projects_Image">
<Image
className='PROJECTS_Projects_image'
src={item['img']}
layout='fill'
// objectFit='contain'
/>
</div>
{/* if someone clicks on this link i want them to go to [project].js and send This item to [projcet].js */}
// LINK -1
<Link href={'/projects/' + PC_EXES.indexOf(item)}>
<a>{item['title']}</a>
</Link>
<p>{item['desc']}</p>
</div>
);
export default function index() {
return (
<div className="PROJECTS_Container">
<div className="PROJECTS_Sub_Container">
<div className="PROJECTS_New">
<h1>Web-Related</h1>
<div className="PROJECTS_Present">
{WEB}
</div>
</div>
<div className="PROJECTS_New">
<h1>Pc apllications</h1>
<div className="PROJECTS_Present">
{PC}
</div>
</div>
</div>
</div>
)
}
then i have a link in this page with link /projectsDisplay/{index_of_item_in_Data.js_List} which then leads to the page below
This projectDisplay.js file is covered in [] so it has the router.query thingie
export default function title({project}) {
return (
<div className='DISPLAY_Container'>
<div className="DISPLAY_Sub_Container">
<div className="DISPLAY_Image">
<Image
// src={`'/${img}'`}
src={'/img/Projects/Cluq.PNG'}
// src={data['img']}
layout='fill'
/>
</div>
<div className="DISPLAY_Info">
<h3>Here also</h3>
SUS
<p>Want data here</p>
</div>
</div>
</div>
)
}
I wanna display the same data the user clicked for in the first page, in simple words the item in the first page shall be accessible here in the last page's HTML
In my project, I am working on the result page of the e-commerce.
I want to retrieve the data from two collections.
One is called "Product", and the other one is called "ProUser".
Now, I could retrieve and show the product info from "Product" collection.
I used v-for loop to show the each item's information.
I also want to retrieve shop name in "ProUser" collection of each user at the same time.
I set the shop name in "business" field.
Product collection is corresponding to uid.
In my dev console, I could confirm I could retrieve all the data from "ProUser" collection.
Following is my vue.js code.
Now in my browser, I cannot show the shop name of each user.
<template>
<div class="main">
<section class="cards">
<div class="card-list" v-for="(item, index) in getMenuItems" :key="index">
<div class="card" >
<div class="product-list" v-if="item.quantity > 0">
<div class="quantity">
<span>{{ item.quantity }}</span>
</div>
<div class="card__image-container" v-for="(sample, index) in item.sample" :key="index">
<router-link to="/product">
<img
:src="sample"
alt="Detailed image description would go here."
class="image"
/>
</router-link>
<!-- Retrieve business name from the ProUser collection. -->
<div class="card__content" v-for="(item, index) in ProUsers" :key="index">
<div class="card__info">
<span class="text--medium">{{ item.business }}</span>
<span class="card__distance text--medium"> product.quantity -- orders </span>
</div>
</div>
</div>
<div class="icons">
<div class="time">
<span>{{ item.limitObject }}</span>
</div>
<div class="fav">
<span>Heart</span>
</div>
<div class="price">
<span>{{ item.sale }}</span>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
import fireApp from '#/plugins/firebase'
const firebase = require("firebase");
require("firebase/firestore");
const db = firebase.firestore();
import googleMapMixin from '#/mixins/googleMapMixin'
import { mapGetters } from 'vuex'
export default {
name: "UserLocation",
data() {
return {
address: "",
error: "",
spinner: false,
ProUsers: []
}
},
mixins: [googleMapMixin],
created() {
//vuexfire
const dbMenuRef = db.collection('Product')
this.$store.dispatch('setMenuRef', dbMenuRef)
//firestore
db.collection("ProUser")
.get()
.then((querySnapshot)=> {
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
this.ProUsers.push(doc.data())
});
})
.catch((error) => {
console.log("Error getting documents: ", error);
});
},
computed: {
...mapGetters([
'getMenuItems'
])
},
methods: {
}
}
</script>
The problem now is, I could see all the shop name in <div class="card__info> tag.
What I want to achieve is to show one shop name of each user in here.
<!-- Retrieve business name from the ProUser collection. -->
<div class="card__content" v-for="(item, index) in ProUsers" :key="index">
<div class="card__info">
<span class="text--medium">{{ item.business }}</span>
<span class="card__distance text--medium"> product.quantity -- orders </span>
</div>
</div>
</div>
Not showing all the shop name.
My question is In other words, I want to fetch the product and the product owner.
Now in one tag, I could show one product with all the product owners in "ProUser" collection.
Hope someone helps me out.
If you need more information, please feel free to ask.
Here's how you can fetch data user from prouser collection and after then fetch the product related to the prouser and create a new object from data from both collection data.
let data = [];
let db = firebase.firestore();
db.collection("ProUser")
.get()
.then((userSnapshot) => {
db.collection("Product")
.get()
.then((productSnapshot) => {
userSnapshot.forEach((user) => {
productSnapshot.forEach((product) => {
if (user.id === product.id) {
data.push({
uid: user.id,
pId: product.id,
...user.data(),
...product.data(),
});
}
});
});
})
.catch((e) => {
console.log(e);
});
})
.catch((e) => {
console.log(e);
});
when I make a call to the unsplash api in the componentDidMount, the this.state.photos data is still undefined after the api call, but when I console.log out the response to the console, the data is showing. You can see thay I have console.log the informations. (response.data and this.state.photos). The this.state.photos is the one being undefined and not showing the data. I am using ReactJS. Anyone know why? Please see code below. Thanks!
import React, { useState, useEffect } from "react";
import Footer from "../components/Footer";
import axios from "axios";
import NavBar from "../components/NavBar";
import AOS from 'aos';
class CountryPage extends React.Component{
state = {
country: null,
photos: []
}
componentDidMount() {
axios.get(`https://restcountries.eu/rest/v2/name/${this.props.match.params.name}`)
.then(response=> {
this.setState({
country: response.data[0]
})
console.log(this.state.country)
})
axios.get(`https://api.unsplash.com/search/photos?client_id=${Access_Key}&query=bike`)
.then(response=> {
this.setState({
photos: response.data[0]
})
console.log(response.data)
console.log(this.state.photos)
})
AOS.init({
duration: 1000
});
}
render() {
if(!this.state.country){
return <p>Loading</p>
}
return(
<div className="countryPageBack">
<NavBar/>
<div className="container">
<div className="countryAndFlag animate__bounceIn">
<h1 className="countryPageTitle">{`${this.props.match.params.name} - (${this.state.country.nativeName})`}</h1>
<img className="countryPageFlag" src={this.state.country.flag}/>
</div>
<div data-aos="fade-left" className="countryBasics">
<h3 className="sectionTitle">Basic Info</h3>
<div className="basicDesc">{`Located in ${this.state.country.region}, ${this.state.country.name} has a population of ${this.state.country.population} people`}</div>
<div className="propertyName">Currency: <span className="propertyValue">{this.state.country.currencies[0].name} - {`${this.state.country.currencies[0].symbol}`}</span></div>
<div className="propertyName">Langauges Spoken: <span className="propertyValue">{this.state.country.languages[0].name}</span></div>
<div className="propertyName">Capitols: <span className="propertyValue">{this.state.country.capital}</span></div>
</div>
<div data-aos="fade-right" className="countryRegion">
<h3 className="sectionTitle">Regional Info</h3>
<div className="propertyName">Region: <span className="propertyValue">{this.state.country.region}</span></div>
<div className="propertyName">Subregion: <span className="propertyValue">{this.state.country.subregion}</span></div>
<div className="propertyName">Timezones: <span className="propertyValue">{this.state.country.timezones}</span></div>
<div className="propertyName">Area: <span className="propertyValue">{this.state.country.area}</span></div>
</div>
<div data-aos="fade-left" className="countryOthers">
<h3 className="sectionTitle">Other Info</h3>
<div className="propertyName">Calling Code: <span className="propertyValue">{this.state.country.callingCodes}</span></div>
<div className="propertyName">Country Code: <span className="propertyValue">{this.state.country.alpha3Code}</span></div>
<div className="propertyName">Main Domain: <span className="propertyValue">{this.state.country.topLevelDomain}</span></div>
</div>
</div>
<Footer/>
</div>
)
}
}
export default CountryPage;
Looks like you are setting the wrong key to the state.
I tried a similar call to Unsplash API (ref) for fetching photos. I believe you should change your set code to
this.setState({
photos: response.data.results[0]
})
in case you want the first photo to be added to photos or response.data.results if you want the entire list.
I've been trying to access the array results from my fetch api request. I can get the results to return and parse it from json into a javascript object. However I cant access the results. The array is that is return called results. I wondering what I'm missing. The ultimate aim of the project is to get 12 random profiles from the api and get it to display to the card div. The error message I'm getting is 'Uncaught (in promise) TypeError: Cannot read property 'results' of undefined at app.js:40'
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Public API Requests</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="css/normalize.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<header>
<div class="header-inner-container">
<div class="header-text-container">
<h1>AWESOME STARTUP EMPLOYEE DIRECTORY</h1>
</div>
<div class="search-container">
</div>
</div>
</header>
<div id="gallery" class="gallery">
</div>
</body>
<script type="text/javascript" src="app.js"></script>
</html>
Javascript
const gallery = document.getElementById('gallery');
const card = document.createElement('div');
card.classList.add('card');
gallery.appendChild(card);
function fetchData(url) {
return fetch(url)
.then(response => { return response.json()})
.then(data => {console.log(data)})
.catch(error => {console.log('Error with fetching API', error)})
}
function generateInfo(data) {
const info = data.map( item => `
<div class="card-img-container">
<img class="card-img" src="${data}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${name.first} ${name.last}</h3>
<p class="card-text">${data.email}</p>
<p class="card-text cap">${location.city}</p>
</div>
`)
card.innerHTML = info;
}
fetchData('https://randomuser.me/api/')
.then(data => generateInfo(data.results));
The error is clear, the object you are getting in data is not defined, that's why it does not have a result key.
Check that data is coming from the URL. When I fetch the URL there is JSON coming in.
Also note that in the second then you have for debugging is not returning the data variable, and that's why you get nothing afterwards.
Add a return statement like: return data;
Extra info related to the catch part from docs: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API if you want to check for errors look at the status code from response.
The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
Change the fetchData function, remove .then block where you are getting final data, attach it when calling fetchData
function fetchData(url) {
return fetch(url)
.then(response => { return response.json()})
.catch(error => {console.log('Error with fetching API',
error)})}
fetchData('https://randomuser.me/api/')
.then(data =>generateInfo(data.results)); //success to the final promise
Now inside generate info use foreach() instead of map().Since for each user object you need to create card.
function generateInfo(results) {
results.forEach( userObj =>{
const card = document.createElement('div');
card.classList.add('card');
card.innerHTML = `
<div class="card-img-container">
<img class="card-img" src="${userObj.picture.thumbnail}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${userObj.name.first} ${name.last}</h3>
<p class="card-text">${userObj.email}</p>
<p class="card-text cap">${userObj.location.city}</p>
</div>
`;
gallery.appendChild(card);
})
}
Run the following snippet to check if it works.
const gallery = document.getElementById('gallery');
function fetchData(url) {
return fetch(url)
.then(response => { return response.json()})
.catch(error => {console.log('Error with fetching API', error)})}
function generateInfo(results) {
results.forEach( userObj =>{
const card = document.createElement('div');
card.classList.add('card');
card.innerHTML = `
<div class="card-img-container">
<img class="card-img" src="${userObj.picture.thumbnail}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${userObj.name.first} ${name.last}</h3>
<p class="card-text">${userObj.email}</p>
<p class="card-text cap">${userObj.location.city}</p>
</div>
`;
gallery.appendChild(card);
})
}
fetchData('https://randomuser.me/api/')
.then(data =>generateInfo(data.results));
<header>
<div class="header-inner-container">
<div class="header-text-container">
<h1>AWESOME STARTUP EMPLOYEE DIRECTORY</h1>
</div>
<div class="search-container">
</div>
</div>
</header>
<div id="gallery" class="gallery">
</div>