Access data / Structure data in ReactJS / Firebase - javascript

I'm a little bit losted coming from Rails to React/Firebase. I have the following realtime database structure. As you can see, a product can have a brand and multiple sellers.
If a brand is true, i'd like to get / display the brand contents on my page (the avatar, name, link etc.). Same for the sellers.
Right now, if i try to display the brand content, i get "true" when i'd like an object containing the infos i've stored in brands or sellers.
So i'd like for example to be able to do something like this :
<p>{this.props.brands.name}</p> (it can only have one brand for now)
As for the sellers i'd like for example to be able to do something like this :
this.state.sellers.map((seller) =>
<div>
<img src={seller.avatar} />
<p>{seller.name}</p>
</div>
);
Here is my firebase realtime database structure (json) :
{
"products": {
"1": {
"name": "Nike HyperAdapt 1.0",
"tagline": "Self-lacing running shoes",
"releaseDate": "20.08.2020",
"brands": {
"Nike": true
},
"thumbnail": "/img/thumbnails/nike-hyperadapt-thumbnail.jpg",
"media": "/img/media/nike-hyperadapt-media-01.jpeg",
"isRaffle": true,
"description": "Nike HyperAdapt 1.0 is Nike's first line of shoes that can lace themselves, thanks to an internal cable system comprised of fishing line and a pressure sensor located in the sole that responds to the weight of your foot as you move with an algorithmic pressure equation.",
"upvote": "169",
"sellers": {
"Shop 01": true,
"Nike": true
}
},
"2": {
"name": "Puma Fi",
"tagline": "Self lacing shoes by Puma",
"releaseDate": "22.08.2020",
"brands": {
"Puma": true
},
"thumbnail": "/img/thumbnails/puma-fi-thumbnail.jpg",
"media": "/img/media/puma-fi-media-01.jpeg",
"isRaffle": true,
"description": "The technology platform Fit Intelligence (Fi) is designed to automate and finetune performance for our footwear. The very first Fi footwear style is a self-lacing training shoe made for workouts and light running.",
"upvote": "88",
"sellers": {
"Shop 01": true,
"Puma": true
}
}
},
"brands": {
"Nike": {
"name": "Nike",
"avatar": "/img/brands/nike-logo.png",
"link": "https://www.nike.com/fr",
"products": {
"1": true
}
},
"Puma": {
"name": "Puma",
"avatar": "/img/brands/puma-logo.png",
"link": "https://eu.puma.com/fr/fr/home",
"products": {
"2": true
}
}
},
"sellers": {
"Shop 01": {
"name": "Shop 01",
"avatar": "/img/sellers/shop-01-logo.png",
"link": "https://www.shop-01.com/",
"products": {
"1": true,
"2": true
}
},
"Nike": {
"name": "Nike",
"avatar": "/img/sellers/nike-store-logo.png",
"link": "https://www.nike.com/fr/launch",
"products": {
"1": true
}
},
"Puma": {
"name": "Puma",
"avatar": "/img/sellers/puma-logo.png",
"link": "https://eu.puma.com/fr/fr/home",
"products": {
"2": true
}
}
}
}
EDIT :
here is what the component that's supposed to show the data looks like :
import React, { Component } from 'react';
import ProductPopup from './ProductPopup';
class ProductItem extends Component {
constructor() {
super();
this.state = {
productPopupStatus: false,
};
}
showProductPopup = () => {
this.setState({ productPopupStatus: true });
};
hideProductPopup = () => {
this.setState({ productPopupStatus: false });
};
renderUpvoteBtn() {
return (
<div className="upvote-btn_wrapper">
<a className="upvote-btn" href="#">
<span className="upvote-counter">
<i className="fas fa-sort-up"></i>
<span>{this.props.upvote}</span>
</span>
</a>
</div>
);
}
renderInfoSession() {
return (
<section className="product-item-info">
<span>
<h2>{this.props.name}</h2>
</span>
<p>{this.props.tagline}</p>
<div className="product-item_meta-shadow"></div>
</section>
);
}
renderMeta() {
return (
<div className="product-item_meta">
<a href="#">
// SHOW ASSOCIATED BRAND AVATAR AND NAME
</a>
</div>
);
}
render() {
return (
<li className="product-item">
{this.renderUpvoteBtn()}
<a href="#" onClick={this.showProductPopup} className="product-item_content">
<img className="product-item-media" src={this.props.media} />
{this.renderInfoSession()}
</a>
{this.renderMeta()}
<ProductPopup status={this.state.productPopupStatus} hidePopup={this.hideProductPopup} />
</li>
);
}
}
export default ProductItem;

It seems like you're getting "true" because your brand name is a boolean. I think it might help by having your brand listed like:
brand: {
name: "Nike"
}
As far as your sellers, I feel that listing them in an array rather than an object would be better as well. You'll only be getting "true" because those values are boolean.
Is there a reason you wanted "sellers" to be an object? If not I would make it an array with objects that hold the info you need.
brands: [
{name: "Brand1", img: "imgsource1"},
{name: "Brand2", img: "imgsource2"}
]

Related

Looping through array, fetching tweets and returning new reversed array javascript react

UPDATE: I have deployed the site for more context you can view it here https://conundrum-quest-rw-rebuild-web.onrender.com/
the public repo is here
https://github.com/wispyco/conundrum-quest-rw-rebuild
Note: the data on the live site is different but the initial load is loading the hero's on the wrong cards, you can compare the quest with subsequent heros on the home page and the returned data from my function below, you can scroll down to see the rendered cards.
You can see that if you click on a card it shows the correct heros on the single page.
I have the following quests data structure that I am looping through in a separate function and running a fetch to request some profile images from twitter.
[
{
"__typename": "Quest",
"id": 5,
"name": "How do we solve mental health related issues?",
"userId": 17,
"heros": [
{
"__typename": "Hero",
"name": "Anders Kitson",
"twitter": "anderskitson"
},
{
"__typename": "Hero",
"name": "ders",
"twitter": "derz_O"
}
]
},
{
"__typename": "Quest",
"id": 6,
"name": "How do we create a world where North Korea participates and collaborates with the rest of the World?",
"userId": 17,
"heros": [
{
"__typename": "Hero",
"name": "Crypto Dude",
"twitter": "phunk2243"
}
]
}
]
Here is my custom hook
const twitter = useFetchTwitterMultipleQuests(quests)
export const useFetchTwitterMultipleQuests = (twitterProfileManyQuests) => {
const [twitter, setTwitter] = useState([])
useEffect(() => {
twitterProfileManyQuests.forEach(async (twitterProfileMany, i) => {
const woop = twitterProfileMany.heros.map(async (twitterProfile) => {
const test = fetch(
`${window.location.origin}/.redwood/functions/twitter`,
{
method: 'POST',
body: JSON.stringify({ twitter: twitterProfile.twitter }),
}
)
.then(function (response) {
// The response is a Response instance.
// You parse the data into a useable format using `.json()`
console.log('test')
return response.json()
})
.then(function (data) {
return data.data.resultAwaited.data
})
const go = await test
return go
})
const june = await Promise.all(woop)
setTwitter((prevState) => {
return [...prevState, june]
})
})
}, [twitterProfileManyQuests])
const reversedTwitter = twitter.reverse()
return reversedTwitter
}
The problem is the reversedTwitter or twitter variable in the end sometimes is in the correct reversed order and sometimes not reversed, and I can't figure out why.
This is the correct order result
[
[
{
"username": "anderskitson",
"profile_image_url": "https://pbs.twimg.com/profile_images/1428160652237889539/I7ZiM_g8_normal.jpg",
"name": "▲nders on a quest 🜸 to see myself 🪞",
"id": "4633808432"
},
{
"profile_image_url": "https://pbs.twimg.com/profile_images/1496985668043436033/NoyLrUys_normal.jpg",
"name": "ders.eth",
"id": "1389695824934834181",
"username": "derz_O"
}
],
[
{
"username": "phunk2243",
"profile_image_url": "https://pbs.twimg.com/profile_images/1536485988767350784/cfP_sPSC_normal.jpg",
"name": "9999999333 (🅱️uilding 35 Phunks) 🔜",
"id": "1355005208259133442"
}
]
]
This is the incorrect order result
[
[
{
"name": "9999999333 (🅱️uilding 35 Phunks) 🔜",
"profile_image_url": "https://pbs.twimg.com/profile_images/1536485988767350784/cfP_sPSC_normal.jpg",
"username": "phunk2243",
"id": "1355005208259133442"
}
],
[
{
"username": "anderskitson",
"profile_image_url": "https://pbs.twimg.com/profile_images/1428160652237889539/I7ZiM_g8_normal.jpg",
"name": "▲nders on a quest 🜸 to see myself 🪞",
"id": "4633808432"
},
{
"username": "derz_O",
"profile_image_url": "https://pbs.twimg.com/profile_images/1496985668043436033/NoyLrUys_normal.jpg",
"name": "ders.eth",
"id": "1389695824934834181"
}
]
]
The reason this matters is how I am rendering the data. I am rendering a Quest from the quests data, then mapping over the heros in a quest which correspond to the twitter profiles.
See Here
{quests.map((quest, i) => (
<QuestCard key={quest.id}>
<Link to={routes.quest({ id: quest.id })} key={quest.id}>
<div>
<h3>{truncate(quest.name)}</h3>
{quest.heros.map((hero, index) => (
<React.Fragment key={hero.id}>
{twitter.length > 0 && twitter[i] && (
<span>
{hero.name}
<p>{twitter[i][index]?.name}</p>
<img
key={i}
src={twitter[i][index]?.profile_image_url}
alt={twitter[i][index]?.name}
/>
</span>
)}
</React.Fragment>
))}
</div>
</Link>
<div className="clear" />
</QuestCard>
))}
Any help would be greatly appreciated, most of what I have done works, but after about three refreshes the ordering breaks. Thanks
Fixed by using a custom service and a custom sdl in redwood instead of using a function and having to create a custom hook for rendering. This was recommended by the RW team from this article
https://redwoodjs.com/docs/how-to/using-a-third-party-api
And you can see my changes here
https://github.com/wispyco/conundrum-quest-rw-rebuild/pull/8/commits/41637813dd50be70e2e89372606c08e39618fa07

I am using Jest to run some test in React. But when I run the test I receive the error " Cannot read property 'dateTime' of undefined

I have multiple test in my file but I will use the first one as an example.
import React from 'react';
import { shallow } from 'enzyme';
import Event from '../Event';
import { mockData } from '../mock-data';
describe('<Event /> component', () => {
let EventWrapper;
beforeAll(() => {
EventWrapper = shallow(<Event event={mockData} />)
})
test('rendered event container', () => {
expect(EventWrapper.find('.event-container')).toHaveLength(1);
});
})
Then here is my React Component file
import React, { Component } from 'react';
class Event extends Component {
state = {
showingDetails: false
}
eventDetails = () => {
const showingDetails = this.state.showingDetails;
if (showingDetails === false) {
this.setState({
showingDetails: true
})
} else {
this.setState({
showingDetails: false
})
}
};
render() {
const { event } = this.props;
const eventISODateTime = new Date(event.start.dateTime);
const eventDate = eventISODateTime.toDateString();
const eventTime = eventISODateTime.toTimeString();
const eventTimeFormatted = `${eventTime.slice(0, 5)} ${eventTime.slice(18)}`;
return <div className="event-container">
<h1 className="event-summary">{event.summary}</h1>
<p className="event-date">{eventDate} </p>
<p className="event-time">{eventTimeFormatted}</p>
<p className="event-location">{event.location}</p>
{this.state.showingDetails && (
<div className="event-details">
<h3 className="about-event">About event:</h3>
<a className="details-link" target="_blank" rel="noreferrer" href={event.htmlLink}>See details on Google Calendar</a>
<p className="event-description">{event.description}</p>
</div>
)}
<button className="show-hide" onClick={() => this.eventDetails()}> {this.state.showingDetails ? 'hide description' : 'show description'} </button>
</div >
}
}
export default Event;
I defined dateTime inside of the render().
I using the same { mockData } for each file . When I load my site either in localhost or on Github gh-pages it works fine and displays the data correctly, so it is just giving me an error when running the test 'npm run test'
Here is the mockData file I am pulling from
const mockData = [
{
"kind": "calendar#event",
"etag": "\"3181161784712000\"",
"id": "4eahs9ghkhrvkld72hogu9ph3e_20200519T140000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=NGVhaHM5Z2hraHJ2a2xkNzJob2d1OXBoM2VfMjAyMDA1MTlUMTQwMDAwWiBmdWxsc3RhY2t3ZWJkZXZAY2FyZWVyZm91bmRyeS5jb20",
"created": "2020-05-19T19:17:46.000Z",
"updated": "2020-05-27T12:01:32.356Z",
"summary": "Learn JavaScript",
"description": "Have you wondered how you can ask Google to show you the list of the top ten must-see places in London? And how Google presents you the list? How can you submit the details of an application? Well, JavaScript is doing these. :) \n\nJavascript offers interactivity to a dull, static website. Come, learn JavaScript with us and make those beautiful websites.",
"location": "London, UK",
"creator": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"organizer": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"start": {
"dateTime": "2020-05-19T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"end": {
"dateTime": "2020-05-19T17:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"recurringEventId": "4eahs9ghkhrvkld72hogu9ph3e",
"originalStartTime": {
"dateTime": "2020-05-19T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"iCalUID": "4eahs9ghkhrvkld72hogu9ph3e#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"eventType": "default"
},
{
"kind": "calendar#event",
"etag": "\"3181159875584000\"",
"id": "3qtd6uscq4tsi6gc7nmmtpqlct_20200520T120000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=M3F0ZDZ1c2NxNHRzaTZnYzdubW10cHFsY3RfMjAyMDA1MjBUMTIwMDAwWiBmdWxsc3RhY2t3ZWJkZXZAY2FyZWVyZm91bmRyeS5jb20",
"created": "2020-05-19T19:14:30.000Z",
"updated": "2020-05-27T11:45:37.792Z",
"summary": "React is Fun",
"description": "Love HTML, CSS, and JS? Want to become a cool front-end developer? \n\nReact is one of the most popular front-end frameworks. There is a huge number of job openings for React developers in most cities. \n\nJoin us in our free React training sessions and give your career a new direction. ",
"location": "Berlin, Germany",
"creator": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"organizer": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"start": {
"dateTime": "2020-05-20T14:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"end": {
"dateTime": "2020-05-20T15:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"recurringEventId": "3qtd6uscq4tsi6gc7nmmtpqlct",
"originalStartTime": {
"dateTime": "2020-05-20T14:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"iCalUID": "3qtd6uscq4tsi6gc7nmmtpqlct#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"eventType": "default"
},
{
"kind": "calendar#event",
"etag": "\"3181161784712000\"",
"id": "4eahs9ghkhrvkld72hogu9ph3e_20200521T140000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=NGVhaHM5Z2hraHJ2a2xkNzJob2d1OXBoM2VfMjAyMDA1MjFUMTQwMDAwWiBmdWxsc3RhY2t3ZWJkZXZAY2FyZWVyZm91bmRyeS5jb20",
"created": "2020-05-19T19:17:46.000Z",
"updated": "2020-05-27T12:01:32.356Z",
"summary": "Learn JavaScript",
"description": "Have you wondered how you can ask Google to show you the list of the top ten must-see places in London? And how Google presents you the list? How can you submit the details of an application? Well, JavaScript is doing these. :) \n\nJavascript offers interactivity to a dull, static website. Come, learn JavaScript with us and make those beautiful websites.",
"location": "London, UK",
"creator": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"organizer": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"start": {
"dateTime": "2020-05-21T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"end": {
"dateTime": "2020-05-21T17:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"recurringEventId": "4eahs9ghkhrvkld72hogu9ph3e",
"originalStartTime": {
"dateTime": "2020-05-21T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"iCalUID": "4eahs9ghkhrvkld72hogu9ph3e#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"eventType": "default"
},
];
export { mockData };

How to Nesting React Components with JSON data

I'm trying to map 4 separate components into their respective rows using JSON data.
You can see the app here - https://stackblitz.com/edit/react-kt1zf8
Data.json
const data = {
"lanes":[
{
"_uid": "001",
"name": "Lane1",
"type": "Toll",
"cars":[
{
"component": "Bmw",
"name": "i8",
"number": "12345",
},
{
"component": "Lambo",
"name": "Aventador",
"number": "214512512",
},
]
},
{
"_uid": "002",
"name": "Lane2",
"type": "Easy Pay",
"cars":[
{
"component": "Fiat",
"name": "i8",
"number": "12345",
},
{
"component": "Dodge",
"name": "Aventador",
"number": "214512512",
},
]
},
]
}
export default data
The Rows are rendered in their own component using the "uid" key from JSON.
Mapping the row data (Lanes & Car Type) is rendering correctly. In the stack blitz, you can see the data in each row is unique.
However, when I try to map the nested data, only the results of the first lane is returning on both rows.
In the Components.jsx, I am using the unique id ("uid") key of the lanes in data.js to determine the lanes but can't figure out what I'm doing wrong. Why are only the first two results showing when they are using the same key?
CarContainer
const CarContainer = (props) => {
return (
<div className="car-container">
{props.data.cars.map(block => Components(block))}
</div>
);
};
export default CarContainer;
LaneInfo
const LaneInfo = () => {
const [laneData, setLaneData] = React.useState(null);
React.useEffect(() => {
setLaneData(data.lanes);
}, []);
return (
<>
{laneData &&
laneData.map((p) => (
<>
<div className="lane">
<div className="space" key={p.uid}>
<div>{p.name}</div>
<div>{p.type}</div>
</div>
</div>
<CarContainer data={p}/>
</>
))}
</>
);
};
export default LaneInfo;

How to access a property of an object which is inside a array assigned to a property of another object?

How to access the name property of the inside the subjects array?
The database is mongodb.
Change for the course model is not possible.
The course model :
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SubjectSchema = new Schema({
name : {
type : String
},
description : {
type : String
},
amount : {
type : Number
},
});
//course schema
const CourseSchema = new Schema({
name: {
type : String
},
code : {
type: String
},
passMark : {
type : Number
},
lectureInCharge : {
type : String
},
subjects : {
type : [SubjectSchema]
}
});
//creating model
const Course = mongoose.model('course', CourseSchema);
module.exports = Course;
code which i want access to the subject details of a course?
I want to display the course details with subject details which is inside the
course details. But subjects are inside an array which is assigned to the subject property of the course object.
It is a react interface.
const courses = this.state.courses;
const updatedCourse = courses.map(function (data, index) {
return (
<div key={index}>
<p> Name : {data.name}</p>
<p> Code : {data.code}</p>
<p> Pass Mark : {data.passMark}</p>
<p> lecture in charge : {data.lectureInCharge}</p>
<p> Subjects : </p>
//Here i want aceess the ame property of the inside the
subjects array?
<p> Subject name : {data.subjects.name}</p>
</div>
)
});
The json of the which retrieve from the database looks like this.
Included to get an idea how the database looks like.
[
{
"_id": "5cf348111b0ffd3bc02304b8",
"name": "Software Engineering",
"code": "SE2019",
"passMark": 75,
"lectureInCharge": "Jhon Smith",
"subjects": [
{
"_id": "5cf348111b0ffd3bc02304b9",
"name": "Computer Architecture",
"description": "PC Architecture x86 and x64",
"amount": 2500
}
],
"__v": 0
},
{
"_id": "5cf358991b0ffd3bc02304ba",
"name": "Computer Networking",
"code": "CN2019",
"passMark": 75,
"lectureInCharge": "Jimmy Perera",
"subjects": [
{
"_id": "5cf358991b0ffd3bc02304bc",
"name": "Wireless Communications",
"description": "Introduction to Wireless Communications",
"amount": 5000
},
{
"_id": "5cf358991b0ffd3bc02304bb",
"name": "Network Technology Project",
"description": "Introduction to Network Technology Project",
"amount": 7000
}
],
"__v": 0
},
{
"_id": "5cf3593d1b0ffd3bc02304c0",
"name": "IM",
"code": "IM2019",
"passMark": 75,
"lectureInCharge": "IMIM Jimmy Perera",
"subjects": [
{
"_id": "5cf3593d1b0ffd3bc02304c2",
"name": "IM Wireless Communications",
"description": " IM Introduction to Wireless Communications",
"amount": 3000
},
{
"_id": "5cf3593d1b0ffd3bc02304c1",
"name": "IM Network Technology Project",
"description": "IM Introduction to Network Technology Project",
"amount": 7700
}
],
"__v": 0
}
]
Since it's an array, you'll need an inner loop (probably another map):
const courses = this.state.courses;
const updatedCourse = courses.map(function (data, index) {
return (
<div key={index}>
<p> Name : {data.name}</p>
<p> Code : {data.code}</p>
<p> Pass Mark : {data.passMark}</p>
<p> lecture in charge : {data.lectureInCharge}</p>
<p> Subjects : </p>
{data.subjects.map(({name}, i) => ( // <===
<p key={i}> Subject name : {name}</p> // <===
)}
</div>
);
});

Trouble getting data from JSON with ReactJS

I have a JSON file like this, named data.json
{
"link_template": "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit={num-results}&country={country-code}",
"links": {
"alternate": "http://www.rottentomatoes.com/movie/box-office/",
"self": "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit=20&country=us"
},
"movies": [
{
"abridged_cast": [
{
"characters": [
"Dominic Toretto"
],
"id": "162652472",
"name": "Vin Diesel"
},
{
"characters": [
"Brian O'Conner"
],
"id": "162654234",
"name": "Paul Walker"
},
{
"characters": [
"Louie Tran"
],
"id": "162684066",
"name": "Tony Jaa"
},
{
"characters": [
"Deckard Shaw"
],
"id": "162653720",
"name": "Jason Statham"
},
{
"characters": [
"Luke Hobbs"
],
"id": "770893686",
"name": "Dwayne \"The Rock\" Johnson"
}
],
"alternate_ids": {
"imdb": "2820852"
},
"critics_consensus": "",
"id": "771354922",
"links": {
"alternate": "http://www.rottentomatoes.com/m/furious_7/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922/cast.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922/reviews.json",
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922/similar.json"
},
"mpaa_rating": "PG-13",
"posters": {
"detailed": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg",
"original": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg",
"profile": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg",
"thumbnail": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg"
},
"ratings": {
"audience_rating": "Upright",
"audience_score": 88,
"critics_rating": "Certified Fresh",
"critics_score": 82
},
"release_dates": {
"theater": "2015-04-03"
},
"runtime": 140,
"synopsis": "Continuing the global exploits in the unstoppable franchise built on speed, Vin Diesel, Paul Walker and Dwayne Johnson lead the returning cast of Fast & Furious 7. James Wan directs this chapter of the hugely successful series that also welcomes back favorites Michelle Rodriguez, Jordana Brewster, Tyrese Gibson, Chris \"Ludacris\" Bridges, Elsa Pataky and Lucas Black. They are joined by international action stars new to the franchise including Jason Statham, Djimon Hounsou, Tony Jaa, Ronda Rousey and Kurt Russell.",
"title": "Furious 7",
"year": 2015
},
{
"abridged_cast": [
{
"characters": [
"Oh"
],
"id": "770702500",
"name": "Jim Parsons"
},
{
"characters": [
"Tip"
],
"id": "351524959",
"name": "Rihanna"
},
{
"characters": [
"Captain Smek"
],
"id": "162654836",
"name": "Steve Martin"
},
{
"id": "162652167",
"name": "Jennifer Lopez"
}
],
"alternate_ids": {
"imdb": "2224026"
},
"critics_consensus": "",
"id": "771315639",
"links": {
"alternate": "http://www.rottentomatoes.com/m/home_2015/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/771315639/cast.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/771315639/reviews.json",
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/771315639.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/771315639/similar.json"
},
"mpaa_rating": "PG",
"posters": {
"detailed": "http://resizing.flixster.com/LO7V_j1xUTlsbwzIyCINBxBm5qE=/54x80/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/17/11181778_ori.jpg",
"original": "http://resizing.flixster.com/LO7V_j1xUTlsbwzIyCINBxBm5qE=/54x80/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/17/11181778_ori.jpg",
"profile": "http://resizing.flixster.com/LO7V_j1xUTlsbwzIyCINBxBm5qE=/54x80/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/17/11181778_ori.jpg",
"thumbnail": "http://resizing.flixster.com/LO7V_j1xUTlsbwzIyCINBxBm5qE=/54x80/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/17/11181778_ori.jpg"
},
"ratings": {
"audience_rating": "Upright",
"audience_score": 69,
"critics_rating": "Rotten",
"critics_score": 47
},
"release_dates": {
"theater": "2015-03-26"
},
"runtime": 93,
"synopsis": "When Oh, a loveable misfit from another planet, lands on Earth and finds himself on the run from his own people, he forms an unlikely friendship with an adventurous girl named Tip who is on a quest of her own. Through a series of comic adventures with Tip, Oh comes to understand that being different and making mistakes is all part of being human. And while he changes her planet and she changes his world, they discover the true meaning of the word HOME. (c) Fox",
"title": "Home",
"year": 2015
}
]
}
This is my ReactJS code, intended to get data from that JSON file and bind in my React components
var CastMember=React.createClass({
render:function(){
<div className="castmember">
</div>
}
});
var Cast=React.createClass({
render:function(){
var cast_members=this.props.cast.map(function (member){
return (
<CastMember member={member}/>
);
});
return (
<div className="cast">
{cast_members}
</div>
);
}
});
var Movie=React.createClass({
render:function(){
return (
<div className="movieBox">
<Cast cast={this.props.movie.abridged_cast}/>
</div>
);
}
});
var MovieList=React.createClass({
render:function(){
var movieNodes=this.props.movies.map(function (movie){
return (
<Movie movie={movie}/>
);
});
return (
<div className="movieList">
{movieNodes}
</div>
);
}
});
var DataBlock = React.createClass({
getInitialState:function() {
return {data:{
movies:[
{abridged_cast:[]}
]
}}
},
componentDidMount:function() {
var a=this;
$.ajax({
url:this.props.url,
dataType:'json',
cache:false,
success:function(data){
this.setState({data:data})
}.bind(this)
});
},
render: function() {
return (
<div className="dataBlock">
<h1>Movie List</h1>
<MovieList movies={this.state.data.movies}/>
</div>
);
}
});
React.render(
<DataBlock url="data.json"/>,
document.getElementById('content')
);
I have been doing this demo in bottom-to-top order. I was able to get list of movies from JSON file and render it, but now stuck in getting abridged_cast in each movie
In render function of Cast component, if I replace it with rendering {this.props.cast}, everything will show up. But I fail in mapping them to member property of CastMember component: My code above didn't display anything. What's wrong with my code?
var CastMember=React.createClass({
render:function(){
<div className="castmember">
</div>
}
});
CastMember component should handle its prop, as you pass the data member to CastMember-> <CastMember member={member}/>.
This would be help:
var CastMember=React.createClass({
render:function(){
return (
<div className="castmember">
{this.props.member}
</div>
);
}
});

Categories