I'm attempting to incorporate video into a flat feed from GetStreamIO. My current approach is to embed a video element from Expo into the content body of the Activity UI component if the post has a video link. Starting with Youtube links only. I'm running into an issue where I'm not able to select the video url when it's available nested in props.activity.attachments. For some reason I cannot directly access the object in the videos array directly without converting the value to JSON. I referenced this StackOverflow Post for the JSON workaround.
My code to check if attachment has video url and grab it if it does
const LikeActivity = (props) => {
if (props.activity.attachments != undefined) {
console.log(props.activity.attachments)
console.log(fetchFromObject(props.activity.attachments, "og"))
var og = fetchFromObject(props.activity.attachments, "og")
var videos = fetchFromObject(og, "videos")
console.log(og)
// Can get the og object but cannot pull video url from it.
}
return (
<Activity
{...props}
Footer={
<View>
// For Now just putting this here to see the video element render. Need to pass URI from Post to element eventually.
<Video
source={{ uri: 'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4' }}
rate={1.0}
volume={1.0}
isMuted={false}
resizeMode="cover"
shouldPlay
isLooping
style={{ width: 300, height: 300 }}
/>
<LikeButton {...props} />
</View>
}
/>
);
};
My App implementation
<StreamApp
apiKey="XXXX"
appId="XXXX"
token="XXXXXX"
>
<FlatFeed
feedGroup="timeline"
userId="user-one"
Activity={LikeActivity}
/>
</StreamApp>
Fetch From Object method
function fetchFromObject(obj, prop) {
if(typeof obj === 'undefined') {
return false;
}
var _index = prop.indexOf('.')
if(_index > -1) {
return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
}
return obj[prop];
}
The feed consists of a number of posts and the props.activity.attachments has the following values at runtime. Each post with a link currently has a rich snippet. The attachments value also recognizes videos vs images. I've also included an image of the feed here as a reference.
Object {
"og": Object {
"description": "Why choose one when you can wear both? These energizing pairings stand out from the crowd",
"images": Array [
Object {
"image": "https://www.rollingstone.com/wp-content/uploads/2018/08/GettyImages-1020376858.jpg",
},
],
"title": "'Queen' rapper rescheduling dates to 2019 after deciding to “reevaluate elements of production on the 'NickiHndrxx Tour'",
"url": "https://www.rollingstone.com/music/music-news/nicki-minaj-cancels-north-american-tour-with-future-714315/",
},
}
undefined
Object {
"og": Object {
"description": "Why choose one when you can wear both? These energizing pairings stand out from the crowd",
"images": Array [
Object {
"image": "https://images.wsj.net/im-21927/TOP",
},
],
"title": "How to Pair Neutrals and Bright Colors",
"url": "https://graphics.wsj.com/glider/marketreport-4a039902-7e0d-4631-ab83-6cc1931c1bc6",
},
}
undefined
Object {
"og": Object {
"description": "Serial entrepreneur Elon Musk wants to fundamentally change the way we live. But his path to success has been characterized by both great accomplishments and flirtations with failure.",
"images": Array [
Object {
"image": "https://static01.nyt.com/images/2018/08/22/us/19xp-musk-vid-2/19xp-musk-vid-2-videoSixteenByNine1050.jpg",
},
],
"title": "Elon Musk’s Highs and Lows: PayPal, SpaceX, Tesla",
"url": "https://www.nytimes.com/video/business/100000006060092/elon-musk-tesla-spacex.html",
},
}
undefined
Object {
"og": Object {
"description": "We are in a Simulation - Elon Musk",
"images": Array [],
"site_name": "YouTube",
"title": "We are in a Simulation - Elon Musk",
"type": "video.other",
"url": "https://www.youtube.com/watch?v=xBKRuI2zHp0",
"videos": Array [
Object {
"height": "360",
"secure_url": "https://www.youtube.com/embed/xBKRuI2zHp0",
"type": "text/html",
"width": "640",
},
],
},
}
Array [
Object {
"height": "360",
"secure_url": "https://www.youtube.com/embed/xBKRuI2zHp0",
"type": "text/html",
"width": "640",
},
]
Object {
"images": Array [
"https://cdn.vox-cdn.com/thumbor/OBDFDT9j-nHEpGLckE4u5ibX2qU=/1400x1400/filters:format(png)/cdn.vox-cdn.com/uploads/chorus_asset/file/13589869/edu_distance_to_the_moon.png",
"https://www.jpl.nasa.gov/images/mars/20170622/PIA01466-16.jpg",
"http://cdn.sci-news.com/images/enlarge4/image_5608_2e-Jupiter.jpg",
"https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/07/SolarFull_SeanDoran_2880FullwidthLede-2880x1620.jpg",
],
}
Related
My goal here is to have the childless nodes contain hyperlinks. This is the D3 plugin I'm basing things off of: https://github.com/deltoss/d3-mitch-tree
Image Example
I'm newer to JS and JSON so I'm having difficulties on figuring out how to proceed, especially since there's little to refer to in regard to hyperlinks & JSON. If there's a better way to go about this, I'm certainly open to new ideas.
Thank you in advance
<script src="https://cdn.jsdelivr.net/gh/deltoss/d3-mitch-tree#1.0.2/dist/js/d3-mitch-tree.min.js"></script>
<script>
var data = {
"id": 1,
"name": "Animals",
"type": "Root",
"description": "A living that feeds on organic matter",
"children": [
{
"id": 6,
"name": "Herbivores",
"type": "Type",
"description": "Diet consists solely of plant matter",
"children": [
{
"id": 7,
"name": "Angus Cattle",
"type": "Organism",
"description": "Scottish breed of black cattle",
"children": []
},
{
"id": 8,
"name": "Barb Horse",
"type": "Organism",
"description": "A breed of Northern African horses with high stamina and hardiness. Their generally hot temperament makes it harder to tame.",
"children": []
}
]
}
]
};
var treePlugin = new d3.mitchTree.boxedTree()
.setData(data)
.setElement(document.getElementById("visualisation"))
.setMinScale(0.5)
.setAllowZoom(false)
.setIdAccessor(function(data) {
return data.id;
})
.setChildrenAccessor(function(data) {
return data.children;
})
.setBodyDisplayTextAccessor(function(data) {
return data.description;
})
.setTitleDisplayTextAccessor(function(data) {
return data.name;
})
.initialize();
</script>
Chain this method before .initialize():
.on("nodeClick", function(event, index, arr) {
if (!event.data.children.length) {
console.log('you clicked a child-less item', event.data);
}
})
Inside the condition, event.data is the clicked childless item. Feel free to place URLs inside those objects and use those URLs to navigate away.
Taken from the repo's /examples folder, where I found one named Advanced example with Node Click Event.
According to the comment on the same page, you can also achieve this using the options syntax:
/* const tree = [
place your data here...
]; // */
new d3.mitchTree.boxedTree({
events: {
nodeClick({ data }) {
if (!data.children.length) {
console.log('You clicked a childless item', data);
}
}
}
})
.setData(tree)
// ...rest of chain
.initialize();
// JSON File
{
"project": [
{
"id": "0",
"title": "Old Portfolio",
"images" :{
"main": "portfolio.png",
"second": ""
},
"content": ["This is one of my first few projects I made as a beginner", "At this project, I learned using JavaScript for making interactive elements like a navbar button. This project was not really something I'm proud of. Hence why I'm making a new portfolio but now with react"]
,
"tags": ["HTML5", "CSS", "JavaScript", "jQuery"]
},
{
"id": "1",
"title": "Twitter Clone",
"images" :{
"main": "twitter_clone.png",
"second": ""
},
"content": ["Project I made to improve my skills in PHP and MySQL.", "At this project, I used MySQL to store data and use PHP to alter what my website will show to the user. I've also used AJAX and JQuery for processing data from MySQL with PHP."]
,
"tags": ["HTML5", "CSS", "JavaScript", "PHP", "MySQL", "jQuery", "AJAX"]
}
]
}
// projectList is from a JSON file
// ProjectList.js
{projectList.map((project) => (
<Projects key={project.id} projectData={project}/>
))}
// Projects.js
const imagePath = "../images/";
const mainImage = imagePath + projectData.images.main
const Projects = ({projectData}) => {
<img style={{
width: "100%",
}} src={mainImage}alt="" />
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I have a JSON file that stores the images. This is gonna be for a list of projects.
The image src is not working and I can't import an image inside the function.
I hope someone could help I am new to React
JSON should not be object, I guess in this case you can use array.
instead of using "img" you must use thumbnail, cause your object(project) has no "img" key, but has "thumbnail"->
const mainImage = imagePath + projectData.thumbnail.main
// JSON File
[
{
"id": "0",
"title": "Old Portfolio",
"thumbnail" :{
"main": "portfolio.png",
"second": ""
},
"content": ["This is one of my first few project I made as a beginner", "At this project I learned using JavaScript for making interactive elements like a navbar button. This project was not really something I'm proud of. Hence why I'm making a new portfolion but now with react"]
,
"tags": ["HTML5", "CSS", "JavaScript", "jQuery"]
},
{
"id": "1",
"title": "Twitter Clone",
"thumbnail" :{
"main": "twitter_clone.png",
"second": ""
},
"content": ["Project I made to improve my skills in PHP and MySQL.", "At this project I used MySQL to store data and use PHP to alter what my website will show to the user. I've also used AJAX and JQuery for processing data from MySQL with PHP."]
,
"tags": ["HTML5", "CSS", "JavaScript", "PHP", "MySQL", "jQuery", "AJAX"]
}
]
// projectList is from a JSON file
// ProjectList.js
{projectList.map((project) => (
<Projects key={project.id} projectData={project}/>
))}
// Projects.js
const imagePath = "../images/";
const mainImage = imagePath + projectData.thumbnail.main
const Projects = ({projectData}) => {
<img style={{
width: "100%",
}} src={mainImage}alt="" />
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I finally found a way,
I put the images on the public folder "public/images/image.png"
and
const Projects = ({projectData}) => {
<img src={`images/${projectData.images.main}`}/>
}
I'm following triggering guidelines in Unsplash documentation. So the endpoint is:
GET /photos/:id/download
This is the photo's example response:
{
"id": "LBI7cgq3pbM",
"width": 5245,
"height": 3497,
"color": "#60544D",
"urls": { ... },
"user": { ... },
"links": {
"self": "https://api.unsplash.com/photos/LBI7cgq3pbM",
"html": "https://unsplash.com/photos/LBI7cgq3pbM",
"download": "https://unsplash.com/photos/LBI7cgq3pbM/download", // don't use this property
"download_location": "https://api.unsplash.com/photos/LBI7cgq3pbM/download?ixid=MnwxMTc4ODl8MHwxfHNlYXJjaHwxfHxwdXBweXxlbnwwfHx8fDE2MTc3NTA2MTM" // use this one ;)
}
}
"Be sure to include any query parameters included in the URL (like the ixid)."
So my question is what is value od ixid=MnwxMTc4ODl8MHwxfHNlYXJjaHwxfHxwdXBweXxlbnwwfHx8fDE2MTc3NTA2MTM and how to get it?
Try the following
const ixid = new URLSearchParams(
new URL("https://api.unsplash.com/photos/LBI7cgq3pbM/download?ixid=MnwxMTc4ODl8MHwxfHNlYXJjaHwxfHxwdXBweXxlbnwwfHx8fDE2MTc3NTA2MTM").search
).get("ixid");
console.log(ixid);
I have a two history objects that are podcasts and articles, i want to display both in the same screen in descending order by which time they were clicked,
Here are the variables of original article and podcast from DB
var { articles, articlesInHistory, podcastsInHistory, podcasts } = this.props.stores.appStore;
Here is my article Object from history: console.log("dataItem", articlesInHistory)
dataItem Array [
Object {
"currentTime": 1585439646,
"id": "156701",
Symbol(mobx administration): ObservableObjectAdministration {
"defaultEnhancer": [Function deepEnhancer],
"keysAtom": Atom {
"diffValue": 0,
"isBeingObserved": true,
"isPendingUnobservation": false,
"lastAccessedBy": 26,
"lowestObserverState": 2,
"name": "appStore#1.articlesInHistory[..].keys",
"observers": Set {},
},
"name": "appStore#1.articlesInHistory[..]",
"pendingKeys": Map {
Symbol(Symbol.toStringTag) => false,
"hasOwnProperty" => false,
"toJSON" => false,
},
"proxy": [Circular],
"target": Object {
"currentTime": 1585439646,
"id": "156701",
Symbol(mobx administration): [Circular],
},
"values": Map {
"id" => "156701",
"currentTime" => 1585439646,
},
},
},
,]
And podcast from history: console.log("dataItem", podcastsInHistory)
dataItem Array [
Object {
"currentTime": 1585439636,
"id": "4",
Symbol(mobx administration): ObservableObjectAdministration {
"defaultEnhancer": [Function deepEnhancer],
"keysAtom": Atom {
"diffValue": 0,
"isBeingObserved": true,
"isPendingUnobservation": false,
"lastAccessedBy": 26,
"lowestObserverState": 2,
"name": "appStore#1.podcastsInHistory[..].keys",
"observers": Set {},
},
"name": "appStore#1.podcastsInHistory[..]",
"pendingKeys": Map {
Symbol(Symbol.toStringTag) => false,
"hasOwnProperty" => false,
"toJSON" => false,
},
"proxy": [Circular],
"target": Object {
"currentTime": 1585439636,
"id": "4",
Symbol(mobx administration): [Circular],
},
"values": Map {
"id" => "4",
"currentTime" => 1585439636,
},
},
},
]
now i want to order the two components using currentTime in condition
for example if this podcast was first then i should return
<PodcastList navigate={navigate} podcast={podcast} key={index} />)
Or if the article is first then show
<SmallArticle key={index} article={article} />
i need them mixed not like articles on top and podcast bottom, i been searching arrays sort but couldn't solve it.
I want a condition based on currentTime and using an id to identify or match objects thanks.
As you don´t know from the data if its an article or a podcast (there is no attribute in your objects that tells you that), you can´t put them in the same list-array.
The only way to know if you should render an Article or a Podcast component is based on what list you are reading.
Keep two indexes, articleIndex = 0 and podcastIndex = 0 (you can keep that in your state), and read the actual article and podcast for respective list, and compare the current time. Then you will know what component to render, and advance the corresponding list index.
In pseudo code:
while articleIndex < articlesList.length && podcastIndex < podcastList.length do:
if articlesList[articleIndex].currentTime < podcastList[pocastIndex].currentTime do:
render <SmallArticle article={articlesList[articleIndex]} key ={articleIndex}/>//render SmallArticle
articleIndex += 1; //advance index
else do:
render <PodcastList podcast={podcastList[postcastIndex]} key={podcastIndex} />
podcastIndex +=1;
when the while statement finishes, is because one of the list has been fully traversed. You need to traverse the rest of the other and render the respect component.
If you show me some of your components code can help you with code in more detail, but I don´t know the context.
I am getting a JSON in response from server:
{
"width": "765",
"height": "990",
"srcPath": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_MERGED_/1273.pdf",
"coverPage": "",
"documents": [
{
"index": "1",
"text": "Archiving Microsoft® Office SharePoint® Server 2007 Data with the Hitachi Content Archive Platform and Hitachi Data Discovery for Microsoft SharePoint",
"type": "doc",
"id": "HDS_054227~201106290029",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_2.png"
}
]
},
{
"index": "11",
"text": "Brocade FCoE Enabling Server I/O Consolidation",
"type": "doc",
"id": "HDS_053732~201105261741",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_2.png"
}
]
}
]
}
And I want to get pagelocation of the children.
Can anyone tell me how to do this?
Hi
i also want to get indexes from this and then want to get pagelocations of that particular children. Can you tell me how would i do that?
And also when i when i am getting indexes array it is returning me ,, only and not the index nos.
I am using following code for that :
indexes=response.documents.map(function(e){ return e.children.index; })
Thanks & Regards
If you're interested in simply retrieving all the page locations, you can do it using filter:
var locations = [];
json.documents.forEach(function(e,i) {
e.children.forEach(function(e2,i2) {
locations.push(e2.pageLocation);
)}
});
// returns flat array like [item1,item2,item3,item4]
You can get an array of arrays using map:
var locations = [];
var locations = json.documents.map(function(e) {
return e.children.map(function(e2) {
return e2.pageLocation;
});
});
// returns 2-dimensional array like [[item1,item2],[item1,item2]]
Your json response is an appropriate javascript object So you can access all elements of the object like you do as in back end.
here, you have an array of object of the type documents and each document object has array of objects of the type children. so
syntax would be
myjson.documents[0].children[0].pagelocation
( = http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png)
will give you the very first page location..
and so on