Truncating titles from reddit API using multi-clamp.js - javascript

I'm trying to use (https://www.npmjs.com/package/multi-clamp)[multi-clamp.js] to clamp/truncate my titles that are being returned from the reddit api.
However, it is only working on the 1st retuned title rather than all of the titles. How would I ensure that the function runs on all of the titles returned from the api and not just the 1st?
const reddit = "https://www.reddit.com/r/upliftingnews.json?raw_json=1&limit=10"
async function getData() {
try {
let response = await fetch(reddit);
let data = await response.json()
return data;
} catch (error) {
console.log("error", error);
}
}
getData()
.then(data => data.data.children)
.then(data => data.map(post => ({
source: post.data.domain,
author: post.data.author,
link: post.data.url,
img: (typeof (post.data.preview) !== 'undefined') ? post.data.preview.images[0].source.url : null,
title: post.data.title,
})))
.then(data => data.map(render))
const app = document.querySelector('#app');
const render = post => {
//console.log(post.data);
const node = document.createElement('div');
node.classList.add('news-item', `news-item--${ post.class }`);
node.innerHTML = `
<a class="news-item-link" href="${post.link}">
<div style="background-image: url('${post.img}')" class="news-item-bg"></div>
<div class="news-item-content">
<h3 class="news-item-source">${post.source}</h3>
<h2 class="news-item-title mb-2">${post.title}</h2>
</div>
</a>`;
app.appendChild(node);
new MultiClamp(document.querySelector('.news-item-title'), {
ellipsis: '...',
clamp: 2
});
}
new MultiClamp.. is where the clamping runs on the title selector but it's only clamping the first returned title, rather than all of them.
How do I get it to run on all titles?

document.querySelector returns only the first element that matches the selector. Since you are executing it on the whole document, it will always get the first title that you appended to the document, and create many new MultiClamps on it.
Instead, you need to select the one new title element in your new node:
function render(post) {
const node = document.createElement('div');
node.classList.add('news-item', `news-item--${ post.class }`);
node.innerHTML = `
<a class="news-item-link" href="${post.link}">
<div style="background-image: url('${post.img}')" class="news-item-bg"></div>
<div class="news-item-content">
<h3 class="news-item-source">${post.source}</h3>
<h2 class="news-item-title mb-2">${post.title}</h2>
</div>
</a>`;
app.appendChild(node);
new MultiClamp(node.querySelector('.news-item-title'), {
// ^^^^
ellipsis: '...',
clamp: 2
});
}
Btw, using innerHTML with unescaped interpolation values opens up your application for XSS attacks. Better build the entire node contents using the DOM API as well.

Related

I have an ID of an object of an API, can i get and print that object?

I made this simple application. There is a homepage where i print movies with an API, and if I click the movie it opens a page with the selected movie info. In the info page I made another Api call. I customized the url so when you click on more info, it returns the id of the object that contains the movie's info. So I made a function that takes the id from the url and confronts it with the one of the call API. if they match, the function returns true. But how am i supposed to get and print the movie info with this data? What would you do? Here is the code:
<template>
<div>
<div v-for="info in movieInfo"
:key="info.id">
{{info.id}}
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'ViewComp',
data() {
return{
movieInfo: [],
}
},
mounted () {
axios
.get('https://api.themoviedb.org/3/movie/popular?api_key=###&language=it-IT&page=1&include_adult=false&region=IT')
.then(response => {
this.movieInfo = response.data.results
// console.log(response.data.results)
})
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
},
methods: {
confrontID(){
var url = window.location.href;
var idUrl = url.substring(url.lastIndexOf('/') + 1);
var idMovie = this.info.id;
if (idUrl === idMovie) {
return true;
}
}
}
}
</script>
<style scoped lang="scss">
/*Inserire style componente*/
</style>
You can get rid of the "return true" on as it will return true if they match. Then instead return the movie info associated with the idUrl
if (idUrl === idMovie) {
return idUrl;
}
Then use that to reference the movie

How to update a row with contenteditable in Vue?

I'm trying to figure out how to get the current changes in a 'contenteditable' and update it in the row that it was changed.
<tbody>
<!-- Loop through the list get the each data -->
<tr v-for="item in filteredList" :key="item">
<td v-for="field in fields" :key="field">
<p contenteditable="true" >{{ item[field] }}</p>
</td>
<button class="btn btn-info btn-lg" #click="UpdateRow(item)">Update</button>
<button class="btn btn-danger btn-lg" #click="DelteRow(item.id)">Delete</button>
</tr>
</tbody>
Then in the script, I want to essentially update the changes in 'UpdateRow':
setup (props) {
const sort = ref(false)
const updatedList = ref([])
const searchQuery = ref('')
// a function to sort the table
const sortTable = (col) => {
sort.value = true
// Use of _.sortBy() method
updatedList.value = sortBy(props.tableData, col)
}
const sortedList = computed(() => {
if (sort.value) {
return updatedList.value
} else {
return props.tableData
}
})
// Filter Search
const filteredList = computed(() => {
return sortedList.value.filter((product) => {
return (
product.recipient.toLowerCase().indexOf(searchQuery.value.toLowerCase()) != -1
)
})
})
const DelteRow = (rowId) => {
console.log(rowId)
fetch(`${import.meta.env.VITE_APP_API_URL}/subscriptions/${rowId}`, {
method: 'DELETE'
})
.then((response) => {
// Error handeling
if (!response.ok) {
throw new Error('Something went wrong')
} else {
// Alert pop-up
alert('Delete successfull')
console.log(response)
}
})
.then((result) => {
// Do something with the response
if (result === 'fail') {
throw new Error(result.message)
}
})
.catch((err) => {
alert(err)
})
}
const UpdateRow = (rowid) => {
fetch(`${import.meta.env.VITE_APP_API_URL}/subscriptions/${rowid.id}`, {
method: 'PUT',
body: JSON.stringify({
id: rowid.id,
date: rowid.date,
recipient: rowid.recipient,
invoice: rowid.invoice,
total_ex: Number(rowid.total_ex),
total_incl: Number(rowid.total_incl),
duration: rowid.duration
// id: 331,
// date: rowid.date,
// recipient: 'new R',
// invoice: 'inv500',
// total_ex: Number(500),
// total_incl: Number(6000),
// duration: 'Monthly'
})
})
}
return { sortedList, sortTable, searchQuery, filteredList, DelteRow, UpdateRow }
}
The commented lines work when I enter them manually:
// id: 331,
// date: rowid.date,
// recipient: 'new R',
// invoice: 'inv500',
// total_ex: Number(500),
// total_incl: Number(6000),
// duration: 'Monthly'
Each cell has content editable, I'm not sure how to update the changed event
The way these run-time js frontend frameworks work could be summarized as "content is the function of data". What I mean is the html renders the data that you send it. If you want the data to be updated when the user changes it, you need to explicitly tell it to do so. Some frameworks (like react) require you to setup 1-way data binding, so you have to explicitly define the data that is displayed in the template, as well as defining the event. Vue has added some syntactic sugar to abstract this through v-model to achieve 2-way binding. v-model works differently based on whichever input type you chose, since they have slightly different behaviour that needs to be handled differently. If you were to use a text input or a textarea with a v-model="item[field]", then your internal model would get updated and it would work. However, there is no v-model for non-input tags like h1 or p, so you need to setup the interaction in a 1-way databinding setup, meaning you have to define the content/value as well as the event to update the model when the html tag content changes.
have a look at this example:
<script setup>
import { ref } from 'vue'
const msg = ref('Hello World!')
</script>
<template>
<h1 contenteditable #input="({target})=>msg=target.innerHTML">{{ msg }}</h1>
<h2 contenteditable>{{ msg }}</h2>
<input v-model="msg">
</template>
If you change the h2 content, the model is not updated because vue is not tracking the changes. If you change through input or h1, the changes are tracked, which will also re-render the h2 and update its content.
TL;DR;
use this:
<p
contenteditable="true"
#input="({target})=>item[field]=target.innerHTML"
>{{ item[field] }}</p>

Is there a way of iterating through objects and only access certain values via their key? - Javascript

So basically, I'm making a request to the newsapi, translate the response in English and then store the translated in an object (Since I only want certain data from the response).
I'm using EJS to pass the data from backend to frontend. I've been stuck on this problem for a while now and have done countless research.
For instance, I only want to access the title in the object, pass it on to the frontend via EJS and use h1 for it. Use h3 for the description and image tag for images etc.
Here's my code:
response.on("end", function () {
const newsData = JSON.parse(newsItems);
for (let i = 0; i < newsData.articles.length; i++) {
async function quickStart() {
try {
const [translation_title] = await translate.translate(newsData.articles[i].title, 'en');
const [translation_desc] = await translate.translate(newsData.articles[i].description, 'en');
const [translation_content] = await translate.translate(newsData.articles[i].content, 'en');
const readMore = newsData.articles[i].url;
const img = newsData.articles[i].urlToImage;
const publishedAt = newsData.articles[i].publishedAt;
const emptyObjArray = {
title: translation_title,
description: translation_desc,
content: translation_content,
datePublished: publishedAt,
url: readMore,
imgURL: img
};
//Testing loop
for (const values in emptyObjArray) {
console.log(emptyObjArray);
}
res.render("newsList", { newsItem: emptyObjArray });
} catch (err) {
console.error();
}
}
quickStart();
}
});
My ejs code:
<section id="headline">
<div class="row">
<div class="col-lg-6">
<h1>Before for loop</h1>
<h1>==============</h1>
<h1><%= newsItem.title %></h1>
<h4><%= newsItem.content %></h4>
<h6>Published : <%= newsItem.datePublished %></h6>
</div>
<div class="col-lg-6">
<img src="<%= newsItem.imgURL %>" alt="" />
</div>
</div>
</section>

VueJS Array Index returns wrong result

I am creating a poetry app where poetry is fetched using an API call.
I fetch data using axios library and do v-for to populate data. I use the index from v-for to populate the image for each poem respectively.
I display 10 results per page using my own custom pagination. Currently, it's only for next button though.
The problem I am facing is when I navigate to Page 2! As I said earlier, that I use v-for's index to display images, it doesn't actually update the index when I move to the next page. As a result, the images are shown same as of page 1.
Code:
new Vue({
el: '#app',
data: {
proxy: 'https://cors-anywhere.herokuapp.com/',
imageIndex: 0,
pagination: {
start: 0,
end: 10,
resPerPage: 10
},
fetchData: [],
fetchImages: []
},
methods: {
paginate() {
this.pagination.start = this.pagination.start + this.pagination.resPerPage;
this.pagination.end = this.pagination.end + this.pagination.resPerPage;
},
async fetchDatas() {
try {
const res = await axios(`${this.proxy}http://poetrydb.org/author,title/Shakespeare;Sonnet`);
if (res) {
this.fetchData = res.data;
}
} catch (error) {
console.log(error);
}
},
async fetchImagess() {
const key = '9520054-7cf775cfe7a0d903224a0f896';
const perPage = 154;
const proxy = ''
const res = await axios(`${this.proxy}https://pixabay.com/api/?key=${key}&per_page=${perPage}`);
this.fetchImages = res.data.hits;
}
},
mounted() {
this.fetchDatas();
this.fetchImagess();
}
});
<div id="app">
<div v-for="(poetry, index) in fetchData.slice(this.pagination.start, this.pagination.end)">
<div>
<img :src="fetchImages[index].largeImageURL.toLowerCase()" style="max-width: 100%;height: auto;max-height: 320px;">
<div>
<h5>{{ poetry.title }}</h5>
<span v-for="(poetryBody, i) in poetry.lines.slice(0, 5)">
{{ i === 4 ? poetryBody.split(',').join('') + '...' : poetryBody }}
</span>
<br>
Read More
</div>
</div>
</div>
<nav style="padding-top: 3em;">
<button #click="paginate()">Next</button>
</nav>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
JSFiddle: http://jsfiddle.net/sanjaybanjade/vnu654gk/9/
As you can see the images doesn't get updated when I goto Page 2! Please help me fix this!
And please ignore the console errors. I am gonna fix them later.
The quick fix would be to calculate the offset in line 4 to update on pagination:
<img v-bind:src="fetchImages[index + pagination.start].largeImageURL.toLowerCase()" style="max-width: 100%;height: auto;max-height: 320px;">
wrong at this line fetchImages[index].largeImageURL.toLowerCase().
Since you are iterating a sliced array of fetchData, it's index is related to sliced array, not original array. So, you should apply pagination slice to your fetchImages too.
When you run fetchData.slice(), it returns a new object. So if you slice out 10 new pieces of poetry, their indexes are still going to be 0-9, since the returned object only has that many items each time.
Why it's not working is because you only slice fetchData on this line fetchData.slice(this.pagination.start, this.pagination.end) but you don't slice the fetchImages what means fetchImages still is the same array it didn't change, meaning that index 0 is still the same image. Best is if you keep them in sync so I would add a pageData and pageImages array's and every time you change the paging you update both of them. like in a updatePageData method
new Vue ({
el: '#app',
data: {
proxy: 'https://cors-anywhere.herokuapp.com/',
imageIndex: 0,
pagination: {
start: 0,
end: 10,
resPerPage: 10
},
fetchData: [],
fetchImages: [],
pageData: [],
pageImages: []
},
methods: {
paginateNext() {
this.pagination.start = this.pagination.start + this.pagination.resPerPage;
this.pagination.end = this.pagination.end + this.pagination.resPerPage;
this.updatePageData()
},
updatePageData () {
this.pageData = this.fetchData.slice(this.pagination.start, this.pagination.end)
this.pageImages = this.fetchImages.slice(this.pagination.start, this.pagination.end)
},
async fetchDatas() {
try {
const res = await axios(`${this.proxy}http://poetrydb.org/author,title/Shakespeare;Sonnet`);
if(res) {
this.fetchData = res.data;
}
} catch(error) {
console.log(error);
}
},
async fetchImagess() {
const key = '9520054-7cf775cfe7a0d903224a0f896';
const perPage = 154;
const proxy = ''
const res = await axios(`${this.proxy}https://pixabay.com/api/?key=${key}&per_page=${perPage}`);
this.fetchImages = res.data.hits;
}
},
mounted() {
Promise.all([
this.fetchDatas(),
this.fetchImagess()
])
.then(() => this.updatePageData())
}
});
<div id="app">
<div v-for="(poetry, index) in pageData">
<div>
<img :src="pageImages[index].largeImageURL.toLowerCase()" style="max-width: 100%;height: auto;max-height: 320px;">
<div>
<h5>{{ poetry.title }}</h5>
<span v-for="(poetryBody, i) in poetry.lines.slice(0, 5)">
{{ i === 4 ? poetryBody.split(',').join('') + '...' : poetryBody }}
</span>
<br>
Read More
</div>
</div>
</div>
<nav style="padding-top: 3em;">
<button #click="paginateNext()">Next</button>
</nav>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

Vuejs set method return to template

I'm new to Vue and I'm stuck at the moment. For the practice I'm making an app for episode checklist for series. The first part of the app searches series and add one of them to a database. Result for the search gives me a result like this: https://i.stack.imgur.com/QuOfc.png
Heres my code with template and script:
<template>
<div class="series">
<ul>
<li v-for="item in series" :key="item.id">
<img :src="image_url+item.poster_path"/>
<div class="info">
{{item.name}}
<br/>
<h5>{{item.id}}</h5>
Start Date: {{item.first_air_date}}
<br/>
{{getEpisodeNumber(item.id)}}
<br/>
{{getSeasonNumber(item.id)}}
</div>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "series",
props: ["series"],
data() {
return {
image_url: "https://image.tmdb.org/t/p/w500",
api_key: {-api key-},
episode_url: "https://api.themoviedb.org/3/tv/",
}
},
methods: {
async getEpisodeNumber(showID) {
const json = await fetch(this.episode_url + showID + this.api_key)
.then((res) => { return res.json() })
.then((res) => { return res.number_of_episodes })
return await json
},
async getSeasonNumber(showID) {
const json = await fetch(this.episode_url + showID + this.api_key)
.then((res) => { return res.json() })
.then((res) => { return res.number_of_seasons })
return await json;
}
},
}
</script>
Methods should return to me a number but they return an object, probably promise object. But when I try to console.log the data in the methods they print a value(int). I need reach this value but I'm stuck. I tried to sort of thinks but it fails every time.
I just create a new component called show and pass item.id to this component. In show component, I use another fetch() to get show data again and now it works like I want.

Categories

Resources