I'm working on a project with React JS , and I want to pass a props to an array ,
This is the Component :
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class TaskItem extends Component {
render() {
const task = this.props.task;
return (
<tr>
<Link to={`/tasks/${task.id}`}>
{task.name}
</Link>
</tr>
);
}
}
export default TaskItem;
I want the value of {task.name} to be in the title of this array :
const todoDB = {
todos : [
{
//Proident tempor est nulla irure ad est
'id' : '561551bd7fe2ff461101c192',
'title' : ' ===> HERE <===' ,
'notes' : 'Id nulla nulla proident deserunt deserunt proident in quis. Cillum reprehenderit labore id anim laborum.',
'startDate': new Date(2018, 8, 3),
'dueDate' : new Date(2018, 8, 5),
'completed': false,
'starred' : false,
'important': false,
'deleted' : false,
'labels' : [1]
}
]
The array and the component are not in the same file
I hope those information enough to understand my problem, THANKS
you could convert the todoDB.todos array to a function ,pass the prop to the function and call it. sth like below:
const todoDB = {
todos: (props) => [{
'id': '561551bd7fe2ff461101c192',
'title': props,
'notes': 'Id nulla nulla proident deserunt deserunt proident in quis. Cillum reprehenderit labore id anim laborum.',
'startDate': new Date(2018, 8, 3),
'dueDate': new Date(2018, 8, 5),
'completed': false,
'starred': false,
'important': false,
'deleted': false,
'labels': [1]
}]
}
console.log(todoDB.todos("this is the title")[0].title)
I'm not entirely clear on your requirements but the following is a function that would generate an array of tasks in the format you provided.
const generateTodoDB = todos => ({
todos: todos.map(todo => ({
'id' : '561551bd7fe2ff461101c192',
'title' : todo.title,
'notes' : 'Id nulla ...',
'startDate': new Date(2018, 8, 3),
'dueDate' : new Date(2018, 8, 5),
'completed': false,
'starred' : false,
'important': false,
'deleted' : false,
'labels' : [1]
})
})
Now you just have to call the generateTodoDB function passing in an array of todos.
const myTodos = [{ title: "Get Milk" }, { title: "Get Bananas" }];
const todoDB = generateTodoDB(myTodos);
generateTodoDB is a so called arrow function. It automatically returns the result of its function because it's body is wrapped in parenthathese. The same is happening here with todos.map.
const fn1 = () => ({ thisObject: "gets returned" })
const fn2 = () => { return { thisObjectDoes: "not return automatically" } }
Related
I'm trying to show relative time to now with momentjs, a few seconds ago, 5 minutes ago, an hour ago, etc... When the html renders, it shows the relative time, I mean, 'a few seconds' o 'an hour ago' depending on how old is the comment but it gets stuck in that state and never updates.
This is my code... Any suggestions?
const components = new Set();
// Force update every component at the same time periodically
setInterval(() => {
for (const comp of components) {
comp.$forceUpdate();
}
}, 60000);
Vue.component("FromNow", {
template: '<span :title="title">{{ text }}</span>',
props: ["date"],
created() {
components.add(this);
},
destroyed() {
components.remove(this);
},
computed: {
text() {
return moment(this.date).fromNow();
},
title() {
return moment(this.date).format("dddd, MMMM Do YYYY, h:mm:ss a");
},
},
});
var app = new Vue({
el: "#app",
data() {
return {
comments: [
{
name: "Obedi1",
id: 1,
timestamp: 1587499864177,
content: "quia et suscipit\nsuscipit recusandae",
},
{
name: "Jhonj2",
id: 2,
timestamp: 1587499872202,
content: "quia et suscipit\nsuscipit recusandae",
},
{
name: "Janek3",
id: 3,
timestamp: 1587499898749,
content: "quia et suscipit\nsuscipit recusandae",
},
{
name: "Markl4",
id: 4,
timestamp: 1587499904071,
content: "quia et suscipit\nsuscipit recusandae",
},
],
};
},
});
<div id="app">
<div v-for="(comment, index) in comments" :key="index">
<h3>{{ comment.name }}</h3>
<from-now :date="comment.timestamp"></from-now>
<p>{{ comment.content }}</p>
<br />
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="main.js"></script>
Computed cannot be used here, a computed property will never update, because return moment(this.date).fromNow(); is not a reactive dependency.
In comparison, a method invocation will always run the function whenever a re-render happens. I would then try to use a method instead of a computed property.
I am trying to display images from a Markdown file especially from the body of the markdown file but unable to see them.
I am using the recommended plugin configuration by the official GatsbyJS documentation for embedding images in Markdown files. However, I am unable to achieve the same. I can view the images from the frontmatter using GraphQL queries but unable to view the body inline images in the markdown file.
const guid = process.env.NETLIFY_GOOGLE_ANALYTICS_ID;
module.exports = {
siteMetadata: {
title: 'Apple Software',
description: 'my theme',
contact: {
phone: '+91 999999999',
email: 'info#abcxyz.com',
},
menuLinks: [
{
name: 'Services',
link: '/services',
},
{
name: 'Team',
link: '/team',
},
{
name: 'Testimonials',
link: '/testimonials',
},
{
name: 'Blog',
link: '/blog',
},
{
name: 'Contact',
link: '/contact',
},
{
name: 'Work',
link: '/work',
},
{
name: 'Courses',
link: '/carousel',
},
{
name: 'Careers',
link: '/careers',
},
],
},
plugins: [
'gatsby-plugin-sass',
'gatsby-transformer-json',
'gatsby-transformer-remark',
'gatsby-plugin-react-helmet',
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/pages`,
name: 'pages',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/data`,
name: 'data',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/images`,
name: 'images',
},
},
{
resolve: 'gatsby-plugin-google-analytics',
options: {
trackingId: guid ? guid : 'UA-XXX-1',
// Puts tracking script in the head instead of the body
head: false,
},
},
`gatsby-plugin-sharp`,
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-images`,
options: {
// It's important to specify the maxWidth (in pixels) of
// the content container as this plugin uses this as the
// base for generating different widths of each image.
maxWidth: 590,
},
},
],
},
},
{
resolve: `gatsby-plugin-mdx`,
options: {
gatsbyRemarkPlugins: [
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 1200,
},
},
],
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/pages`,
},
},
],
};
and here is the markdown file
---
path: '/services/accounting'
title: 'Accounting'
date: 2018-11-18T12:33:46+10:00
image: 'services/default.png'
---
Lorem markdownum aequalis strigis. _Saetigeri iubeas_, vultu huic alvum nondum
de obside ut laniavit arbor palmis, cum quin. Rupes vetat videndo, armigerae
crimen habet Priamum nec.
## Ne verba patulosque numen vix libet
![Default Image](./default.png)
Agitabitur signa lympha; non lacunae, mox cum tumulis quoque triste dictis.
Ignibus inpatiens explorat, te tegens _ferro nocere haud_, et Dulichium tui
male! Quo sed [fuit flexit et](#vexant-achivi) hic die solido, gloria?
1. Cum det dixit Parcarum qui spemque est
2. Exit ex huic
3. Quod consiste agitataque claustraque vicina videt lacertis
4. Loquor videt
5. Ardua non igne caelesti coniugis cognovi diversorum
6. Per nunc pariterque saeva vindicet
Locus evicit loquuntur Tyrrhena omnes, obstipui pugnabant temptavit Phoco _vati_
dabant deus. Memorata haberet sepulcrales gentisque dum sic, in flumina templa!
Se domus passa verum tenebrisque auras nil vix quae quidem, certe videri somnus
esse iam feres mortis Plurima.
## Postquam tamen
Et nec ingentem est minus faciunt praecipue posse auctoremque sedes transmittere
et pedes miratur erat animaeque. Tellus admonuit humanam funes, sagittis et
licet! Inserui quamvis Clymeni.
- Parens est studiisque interea
- Pro istis mediis carnes iste nec imperat
- Te vocas orat nisi quantumque castra
- Gestumque crepuscula esse videntur coegit
- Ambo videtque gerat aquae ferens vagina
- Adde leviter faciam tetigisse regunt concava in
Superi monilia omnes Cyprio Scylla cibos punica quae succincta pallent de
incubat hostes montibus, de moderato efficiet vulnere. Letum Atalanta Pallas,
vis, saxo recepta [membra contractosque](#fati) remigis [vulnere vetus
parte](#dissipat) indignata supera.
The image in the frontmatter (Header) is working fine. But the same image (default.png) is not showing up from the body of this markdown file.
Currently on a blog website like I got a problem I didn't expect when I start building it...
I build it like this:
• A admin area where you have to login where you can write/delete articles.
• A public area where you don't need to login where you can see the articles write in the admin area.
My database is build like below as you can see every user got a $uid. So because of how it's build my service look like this:
{
"articles" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORxrYnctixsx5sQ5DM" : {
"author" : "Zinedine Zidane",
"categories" : [ "Football", "Tennis" ],
"content" : "<p>Constituendi autem sunt qui sint in amicitia fines et quasi termini diligendi. De quibus tres video sententias ferri, quarum nullam probo, unam, ut eodem modo erga amicum adfecti simus, quo erga nosmet ipsos, alteram, ut nostra in amicos benevolentia illorum erga nos benevolentiae pariter aequaliterque respondeat, tertiam, ut, quanti quisque se ipse facit, tanti fiat ab amicis.Constituendi autem sunt qui sint in amicitia fines et quasi termini diligendi. De quibus tres video sententias ferri, quarum nullam probo, unam, ut eodem modo erga amicum adfecti simus, quo erga nosmet ipsos, alteram, ut nostra in amicos benevolentia illorum erga nos benevolentiae pariter aequaliterque respondeat, tertiam, ut, quanti quisque se ipse facit, tanti fiat ab amicis.</p>",
"date" : 1539158014424,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41666967_311898482736538_5532086598150712503_n.jpg?alt=media&token=6b13fe37-357e-45db-8d0e-4436e166d359",
"name" : "Thalassio otium quem et hortaretur. \t"
},
"-LORy85GKdT9U9p_Iolk" : {
"author" : "David Kidouille",
"categories" : [ "Football", "ChatMignon" ],
"content" : "<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>",
"date" : 1539158086263,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/36981961_1869531810009121_4498273348232413184_n.jpg?alt=media&token=47fc2e67-d198-4533-8939-abc5d3dbed51",
"name" : "Omni habere atque perpetuae sic."
},
"-LOTQNaI7ry3WRavCjNt" : {
"author" : "Sophia Green",
"categories" : [ "Espresso", "Title" ],
"content" : "<p>Harum trium sententiarum nulli prorsus assentior. Nec enim illa prima vera est, ut, quem ad modum in se quisque sit, sic in amicum sit animatus. Quam multa enim, quae nostra causa numquam faceremus, facimus causa amicorum! precari ab indigno, supplicare, tum acerbius in aliquem invehi insectarique vehementius, quae in nostris rebus non satis honeste, in amicorum fiunt honestissime; multaeque res sunt in quibus de suis commodis viri boni multa detrahunt detrahique patiuntur, ut iis amici potius quam ipsi fruantur.</p><p>Ibi victu recreati et quiete, postquam abierat timor, vicos opulentos adorti equestrium adventu cohortium, quae casu propinquabant, nec resistere planitie porrecta conati digressi sunt retroque concedentes omne iuventutis robur relictum in sedibus acciverunt.</p><p>Non ergo erunt homines deliciis diffluentes audiendi, si quando de amicitia, quam nec usu nec ratione habent cognitam, disputabunt. Nam quis est, pro deorum fidem atque hominum! qui velit, ut neque diligat quemquam nec ipse ab ullo diligatur, circumfluere omnibus copiis atque in omnium rerum abundantia vivere? Haec enim est tyrannorum vita nimirum, in qua nulla fides, nulla caritas, nulla stabilis benevolentiae potest esse fiducia, omnia semper suspecta atque sollicita, nullus locus amicitiae.</p>",
"date" : 1539182528987,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/37112713_499156913858390_6321776699583234048_n.jpg?alt=media&token=dea02d84-dcc8-427e-92d1-92529499e052",
"name" : "Plerisque honoribus inventu in verae descendant quas in graves enim"
}
}
},
"contact" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"adress" : "Bla Bla Bla",
"email" : "michel#gmail.com",
"facebook" : "www.facebook.com",
"phone" : "0606060606"
}
},
"evenements" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORx0d49L5W1OHbaPkz" : {
"content" : "<p>Eodem tempore Serenianus ex duce, cuius ignavia populatam in Phoenice Celsen ante rettulimus, pulsatae maiestatis imperii reus iure postulatus ac lege, incertum qua potuit suffragatione absolvi, aperte convictus familiarem suum cum pileo, quo caput operiebat, incantato vetitis artibus ad templum misisse fatidicum, quaeritatum expresse an ei firmum portenderetur imperium, ut cupiebat, et cunctum.</p>",
"dateEnd" : "20/08/1995",
"dateStart" : "17/08/1995",
"name" : "Stand de tir au pigeon",
"place" : "33 rue de la Liberté, Bourgoin Jallieu"
}
}
},
"medias" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORymdySlsQ82_rZ6kk" : {
"description" : "Bla Bla Bla Bla",
"titre" : "30 ans de michel",
"type" : "image",
"url" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41466540_333985383837957_6494746608337518152_n.jpg?alt=media&token=079311d7-c42e-4e21-933e-36573e88a893"
},
"-LORyzf8ft5hS_MV_B10" : {
"description" : "klsjbvsjdkbvjkshd",
"titre" : "Bla Bla bla",
"type" : "image",
"url" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41532985_724838064517122_5880047170186967403_n.jpg?alt=media&token=86632def-47b3-4b30-84c9-c9af571da17d"
}
}
},
"sports" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORzZ2xq_JszbFaFyyn" : {
"description" : "<p>Nec vox accusatoris ulla licet subditicii in his malorum quaerebatur acervis ut saltem specie tenus crimina praescriptis legum committerentur, quod aliquotiens fecere principes saevi: sed quicquid Caesaris implacabilitati sedisset, id velut fas iusque perpensum confestim urgebatur impleri.</p>",
"handisport" : "<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>",
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/42004027_2218122771593693_1511293494740179714_n.jpg?alt=media&token=430ddee9-a818-44ac-b80c-2483be38f1c0",
"name" : "Football",
"nbrPlayer" : 10,
"partTime" : 30
}
}
}
}
My Service in the Admin Area where I can access the $uid
import { Injectable } from '#angular/core';
import { filter, map, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { AngularFireDatabase } from 'angularfire2/database';
import { Store } from '../../store';
import { AuthService } from './auth.service';
export interface Article {
name: string,
author: string,
categories: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
#Injectable()
export class ArticlesService {
articles$ = this.db.list<Article>(`articles/${this.uid}`).snapshotChanges()
.pipe(map(actions =>
actions.map(a => ({ key: a.key, ...a.payload.val() }))
))
.pipe(tap(next => {
this.store.set('articles', next);
})
);
constructor(
private store: Store,
private db: AngularFireDatabase,
private authService: AuthService
) {}
get uid() {
return this.authService.user.uid;
}
getArticle(key: string) {
if (!key) return of({});
return this.store.select<Article[]>(`articles`)
.pipe(filter(Boolean))
.pipe(map(articles => articles.find((article: Article) => article.key === key)));
}
addArticle(article: Article) {
return this.db.list(`articles/${this.uid}`).push(article);
}
updateArticle(key: string, article: Article) {
return this.db.object(`articles/${this.uid}/${key}`).update(article);
}
removeArticle(key: string) {
return this.db.list(`articles/${this.uid}`).remove(key);
}
}
My Service in the Admin Area where I can't access the $uid
import { Injectable } from '#angular/core';
import { filter, map, tap } from 'rxjs/operators';
import { of } from 'rxjs';
import { AngularFireDatabase } from 'angularfire2/database';
import { Store } from '../../store';
export interface Article {
name: string,
author: string,
category: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
#Injectable()
export class ArticlesService {
articles$ = this.db.list<Article>(`articles`).snapshotChanges()
.pipe(map(userId =>
userId.map(a => ({ ...a.payload.val() }))
)).pipe(tap(next => {
this.store.set('articles', next);
}));
constructor(
private store: Store,
private db: AngularFireDatabase
) {}
getArticle(key: string) {
if (!key) return of({});
return this.store.select<Article[]>(`articles`)
.pipe(filter(Boolean))
.pipe(map(articles => articles.find((article: Article) => article.key === key)));
}
}
So When I call the service for get my articles in the admin area I get and in the public area I get.
I find a way to get the value but with this way I lose the key object.
export interface Article {
name: string,
author: string,
category: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
How can I get the same object in the visitor area as I get in the admin area ?
I create an Meteor application where have two collections, ActivityCards and Users. I have a reference to the User inside my ActivityCard collections like this:
{
"_id" : "T9QwsHep3dMSRWNTK",
"cardName" : "Guntnauna",
"activitycardType" : 10,
"startDate" : "1952-08-09",
"remainingHours" : 0,
"activities" : [
{
"activityName" : "Cfuw",
"activityTotal" : "5",
"activityEmployee" : "Smamnktl",
"activityDate" : "1960-07-16"
},
...
],
"customerID" : "z9hXczmWaf7wgdAtj",
"isArchived" : 0
}
customerID contains an id to the following user collection:
{
"_id" : "9mXAZkmfpKMPvQY8Y",
"createdAt" : ISODate(),
"services" : {
"password" : {
"bcrypt" : ""
}
},
"emails" : [
{
"address" : "topony#mailinator.com",
"verified" : false
}
],
"profile" : {
"relationNumber" : "962",
"companyName" : "Snider Kinney Co",
"locationStreet" : "Ullamco eaque consequatur aspernatur consectetur eiusmod eligendi enim rerum consectetur asperiores officia eius itaque expedita dolorum",
"locationPostal" : "Sit inventore asperiores est anim commodo non fugiat consequat Voluptatem tempore sunt culpa magni",
"locationCity" : "Ipsum et fugit pariatur Nobis eveniet neque veniam perferendis eius ut quo excepteur consequatur voluptatem architecto",
"contactName" : "Julian Moran",
"contactPhone" : "+388-14-8339022",
"isArchived" : 0
},
"roles" : {
"customers" : [
"customer"
]
}
}
I am new to MongoDB and don't know if this is a properly configured relation In the documentation I mostly find relations from parent to child and not the other way around.
I am wondering what would you guys suggest for this type of relation.
How to save them, get the data from both collections, etc.
If my code can be used I would like to know how to get the relations from child to parent and display them. currently I only used the find() method from MongoDB and mapped the data into separate values.
You can have such a relation in your mongodb collection. If you are using mongoose you can define them in your schema like this:
customerId:{{ type: mongoose.Schema.ObjectId, ref: 'user' }}
and you can reach the parent from child with mongoose populate.
for more information see
https://mongoosejs.com/docs/populate.html
I'm trying to build an interactive banner that when you hover over the banner, you can hover over each image and see a snippet of text.
Im trying to make this snippet of text appear in my div titled 'textbox' only im struggling to make it change when the mouse leaves each image (you will have to see my fiddle for an example)
Let each image load BEFORE hovering over the html blue box...
http://jsfiddle.net/uEDBA/3/
jQuery
$(document).ready(function () {
$(function () {
var people = [{
id: 1,
name: 'Adam',
bio: 'This is Adam\'s Biography. Sed ut perspiciatis unde omnis iste natus error sit voluptatem',
image: 'justin.jpg'
}, {
id: 2,
name: 'Brian',
bio: 'This is Brian\' Biography. Sed ut perspiciatis unde omnis iste natus error sit voluptatem',
image: 'chris.jpg'
}, {
id: 3,
name: 'Charlie',
bio: 'This is Charlie\'s Biography. Sed ut perspiciatis unde omnis iste natus error sit voluptatem',
image: 'sam.jpg'
},
];
w = 750;
h = 450;
var counter = 0;
(function nextFade() {
counter++;
var data = people[Math.floor(Math.random() * people.length)];
var figure = $('<figure style="float:left; width:150px; height:150px; background:red;" />');
var information = '<img src="http://www.placekitten.com/150/150" /><figcaption><h6>Meet ' + data.name + '</h6><p>' + data.bio + '</p>Read about ' + data.name + '. </figcaption>';
figure.html(information).appendTo('.interactive-banner-faces').hide().fadeIn(100, function () {
if (counter < 15) {
nextFade();
} else {
$('.interactive-banner-faces').children(':nth-child(12n+1), :nth-child(12n+2), :nth-child(12n+3)').addClass('rightTxt');
// On mouseover, fadeout the text overlay so we can play with the banner
$('.interactive-banner').on('mouseenter', function () {
$('.textbox').html(data.bio).fadeIn();
$('.overlay').stop().animate({
'top': '-450px'
}, 200, 'easeInCirc');
}).on('mouseleave', function () {
$('.textbox').html('').fadeOut();
$('.overlay').stop().animate({
'top': '0'
}, 600, 'easeOutCirc');
});
};
});
})();
});
});