How to access certain element of nested objects in react - reactjs

I'm struggling to take certain value out of an API. I have no trouble mapping over the parts that I can immediately access using items.value, but when I can't get some of the more nested info. I'm specifically trying to access the value of "quantity" inside of pricing.
Here's my code
import "./StoreDisplay.css"
class StoreDisplay extends Component {
constructor(props) {
super(props)
this.state = {
error: undefined,
isLoaded: false,
items: []
}
}
componentDidMount() {
this.getData();
}
getData() {
fetch(url)
.then((res) => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result,
});
console.log(result)
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div id = "storeDisplay">
<ul className = "container">
{items.map(item => (
<li key = {item.title}>
<div className = "bundleName"> {item.title} {item.pricing.quantity}</div><img src = {item.asset} className = "img"></img>
</li>
))}
</ul>
</div>
);
}
}
}
Sample part of JSON from API:
[
{
"title": "100-Pack Bundle",
"desc": "",
"tag": "",
"purchaseLimit": 1,
"isAvailable": true,
"expireTimestamp": 1662538288,
"shopType": "specials",
"originalPrice": 10500,
"pricing": [
{
"ref": "Apex Coins",
"quantity": 6700
}
],
"content": [
{
"ref": "weapon_charm_charm_apex_asset_v22_misc_pathfinderemoji01",
"name": "MRVN Monitor",
"quantity": 1
},
{
"ref": "pack_cosmetic_rare",
"name": "Apex Pack",
"quantity": 100
}
],
"offerID": "220823_100-pack_bundle",
"asset": "https:\/\/shop-cdn.mozambiquehe.re\/dl_store_s14_0_bund_epic_100pack_a189.png"
},

It looks like item.pricing is actually an array of objects. From here you have a couple of choices, depending on what you want to do.
item.pricing will only ever have one element.
In this case, you can just take the first element:
<div className = "bundleName"> {item.title} {item.pricing[0].quantity}</div>
You want to list all the quantities
<div className = "bundleName"> {item.title} {item.pricing.map(pricing => pricing.quantity).join(" ")}</div>
or
<div className = "bundleName"> {item.title} {item.pricing.map(pricing => pricing.quantity).join(", ")}</div>
You want to have the sum of all quantities
<div className = "bundleName"> {item.title} {item.pricing.map(pricing => pricing.quantity).reduce((a, b) => a + b, 0)}</div>

Related

Display Array Data through map in react Typescript

I try to display Array data but does not display the data on the React web page. AnyOne guide me where is my mistake and correct me. Please see the comment line //
/* eslint-disable */
import React, { Component } from 'react';
import axios from 'axios';
class RestaurantList extends Component<{}, any> {
constructor(props: any) {
super(props);
this.state = { restoLists: null };
}
componentDidMount() {
axios.get("http://localhost:3030/restauranst")
.then((response) => {
this.setState({ restoLists: response.data })
console.log(response);
})
.catch((error) => console.error(error));
}
render() {
console.log(this.state.restoLists);
return (
<div>
<h1>RestaurantList</h1>
{
this.state.restoLists ?
<div>
<ul>
{
this.state.restoLists.map((itme: any) => {
console.log(itme.name); // work this line
<li>
{itme.name} {/**Does not work this line */}
</li>
})
}
</ul>
</div>
:
<p>Please Wait...</p>
}
</div>
);
}
}
export default RestaurantList;
API Response
{
"data": [
{
"id": 1,
"name": "Pizza Hut",
"address": "Dwarka Sector-14",
"rating": "4.5",
"email": "pizzhut#pizza.com"
},
{
"id": 2,
"name": "Mc-Dondle",
"address": "Dwarka Sector-15",
"rating": "4.0",
"email": "mcdondle#mcdon.com"
}
],
"status": 200,
"statusText": "OK",
"headers": {
"cache-control": "no-cache",
"content-type": "application/json; charset=utf-8",
"expires": "-1",
"pragma": "no-cache"
},
"config": {
"url": "http://localhost:3030/restauranst",
"method": "get",
"headers": {
"Accept": "application/json, text/plain, */*"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
},
"request": {}
}
You are not returning anything inside the map.
this.state.restoLists.map(({id, name}: any) => {
return <li key={id}>{name}</li>;
});
Also you can use shorthand method of arrow function,
this.state.restoLists.map(({id, name}: any) => <li key={id}>{name}</li>);
Return from your map function as you are missing return. and loader also try to use through state. By default make isLoadding to false
state
this.state = { restoLists: null, isLoadding : false };
componentDidMount() {
this.setState({isLoading: true})
axios
.get("http://localhost:3030/restauranst")
.then((response) => {
this.setState({ restoLists: response.data, isLoading: false})
}).catch((error) => console.error(error));
}
JSX
const { restoLists } = this.state;
return(
<div>
{isLoadding ? <ul>
{restoLists && restoLists.map(({id, name}: any) => {
return <li key={id}>{name}</li>;
});
}
</ul>
:<p>Loading...</p>}
</div>
)
You were just missing parenthesis inside the return block of your map method:
this.state.restoLists.map((itme: any) => {(
<li>
{itme.name}
</li>
)})

How do I loop an array in React Native

The RSS feed is parsed into an array, but the promblem is, the array doesn't loop, it only shows 1 item. How do I loop my Feeds array?
This is my code, I use react-native-rss-parser (https://www.npmjs.com/package/react-native-rss-parser):
class TNScreens extends React.Component {
state = {
feed: [],
title: []
};
componentDidMount() {
return fetch("https://vnexpress.net/rss/tin-moi-nhat.rss")
.then(response => response.text())
.then(responseData => rssParser.parse(responseData))
.then(rss => {
for (let i = 0; i < rss.items.length; i++) {
this.setState(prevState => ({
...prevState,
feed: rss.items[i],
title: rss.items[i].title
}));
}
});
}
render() {
const Feeds = ([
{
pic: {uri: ''},
title: Object.keys(this.state.title).map(i => this.state.title[i])
}
]);
return (
<SafeAreaView>
<ScrollView>
<Text h2 h2Style={styles.h2Style}>
Trang nhất
</Text>
<Text h4 h4Style={styles.h4Style}>
Cập nhật siêu nhanh
</Text>
<View>
{Feeds.map(({ pic, title }) => (
<Tile
imageSrc={pic}
height={200}
activeOpacity={0.9}
title={title}
titleNumberOfLines={1}
titleStyle={styles.title}
featured
key={title}
/>
))}
</View>
</ScrollView>
</SafeAreaView>
);
}
}
export default TNScreen;
UPDATE
console.log(rss) result:
Object {
"authors": Array [],
"categories": Array [],
"copyright": undefined,
"description": "VnExpress RSS",
"image": Object {
"description": undefined,
"height": undefined,
"title": "Tin nhanh VnExpress - Đọc báo, tin tức online 24h",
"url": "https://s.vnecdn.net/vnexpress/i/v20/logos/vne_logo_rss.png",
"width": undefined,
},
"items": Array [],
"itunes": Object {
"authors": Array [],
"block": undefined,
"categories": Array [],
"complete": undefined,
"explicit": undefined,
"image": undefined,
"newFeedUrl": undefined,
"owner": Object {
"email": undefined,
"name": undefined,
},
"subtitle": undefined,
"summary": undefined,
},
"language": undefined,
"lastPublished": "Sat, 30 Nov 2019 21:28:12 +0700",
"lastUpdated": undefined,
"links": Array [
Object {
"rel": "",
"url": "https://vnexpress.net/rss/tin-moi-nhat.rss",
},
],
"title": "Tin mới nhất - VnExpress RSS",
"type": "rss-v2",
}
There is a problem in your code in for loop you are just replacing the state with one value you are not copying the previous state. You will have to
this.setState(prevState => ({
...prevState,
feed: [...prevState.feed, rss.items[i]],
title: [...prevState, rss.items[i].title]
}));
But this is not the best practice because on every iteration your render will re-render so the best practice is
const feeds = rss.items.map(item => item);
const titles = rss.items.map(item => item.title);
this.setState({ feed: feeds, title:titles });
your this.state.x only save one item, change the code to the following:
and you should also change the get Data method, please do not setState in a loop
componentDidMount() {
return fetch("https://vnexpress.net/rss/tin-moi-nhat.rss")
.then(response => response.text())
.then(responseData => rssParser.parse(responseData))
.then(rss => {
let copyRess = []
let copyTitle = []
for (let i = 0; i < rss.items.length; i++) {
copyRess.push(rss.items[i]);
copyTitle.push(rss.items[i].title)
}
this.setState(prevState => ({
...prevState,
feed: copuRess,
title: copyTitle
}));
});
}
render() {
const Feeds = []
this.state.title.map(element => {
Feeds.push({pic:"",title:element})
})
....

How to use FetchAPI nested Arrays of same object

I am trying to show menu where it can have parent child relationship, with flat structure it is working fine but with nested objects not able to do it.
The below is the JSON and reactJS code.
JSON -
{
"data": [
{
"to": "#a-link",
"icon": "spinner",
"label": "User Maintenance"
},
{
"content": [
{
"to": "#b1-link",
"icon": "apple",
"label": "System Controls"
},
{
"to": "#b2-link",
"icon": "user",
"label": "User Maintenance"
}
],
"icon": "gear",
"label": "System Preferences"
},
{
"to": "#c-link",
"icon": "gear",
"label": "Configuration"
}
]
}
ReactJS code -
export default class MenuComponent extends Component {
constructor() {
super();
this.state = {}
}
componentDidMount(){
fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc')
.then(response => response.json())
.then(parsedJSON => parsedJSON.data.map(menu => (
{
to: `${menu.to}`,
icon: `${menu.icon}`,
label: `${menu.label}`
// content: `${menu.content}`
}
)))
.then(content => this.setState({
content
}))
}
render() {
console.log('333');
console.log(this.state.content);
return (
<MetisMenu content={this.state.content} activeLinkFromLocation />
)
}
}
In JSON you can see the 'System Preference' has nested content.
Try this code
class MenuComponent extends Component {
constructor() {
super();
this.state = {
content : []
}
}
componentDidMount(){
fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc')
.then(response => response.json())
.then(parsedJSON => parsedJSON.data.map(menu => (
{
to: `${menu.to}`,
icon: `${menu.icon}`,
label: `${menu.label}`
// content: `${menu.content}`
}
)))
.then(content => this.setState({
content
}))
}
render() {
const {content} = this.state
if(content === undefined){
return <div>Content not found</div>;
}
if(content.length === 0){
return <div>Loading</div>;
}
return (
<MetisMenu content={content} activeLinkFromLocation />
)
}
}
export default MenuComponent

Pass an items prop with the items within the category key

I can't seem to pass certain items into an item prop if they relate to the category that I am looping through
I have a JSON like this:
{
"Categories": [
{
"Name": "Music",
},
{
"Name": "Comedy",
},
{
"Name": "Sport",
},
{
"Name": "Family",
},
],
"Items": [
{
"Name": "Dolly Parton",
"NameId": "dolly-parton",
"Category": "Music",
},
{
"Name": "Cee Lo Green",
"NameId": "cee-lo-green",
"Category": "Music",
},
{
"Name": "Take That",
"NameId": "take-that",
"Category": "Music",
},
{
"Name": "Football",
"NameId": "football",
"Category": "Sport",
},
{
"Name": "Hockey",
"NameId": "hockey",
"Category": "Sport",
}
]
}
I'm looping through all the categories and then printing them into a list while trying to only pass items that relate to that category in an items prop. I have the code below but it is passing all my data to each element and I'm not sure why.
class CategoryItems extends Component {
constructor(props) {
super(props);
}
state = {
items: this.props.items,
categories: this.props.categories,
};
render() {
const items = this.state.items;
return (
<section className="category-wrapper">
<div className="container">
<div className="category-wrapper__inner">
{this.state.categories.map((category, index) => (
<CategoryItem
key={category.Name}
items={items.map((item, index) => {
item.Category === category.Name ? item : '';
})}
/>
))}
</div>
</div>
</section>
);
}
}
All the data is there and in the react dev-tools it says each element has 667 items but I know there should only be 7 items on the sports category.
Apply a filter instead of a map.
<CategoryItem
key={category.Name}
items={items.filter(i => item.Category === category.Name)}
/>
You can try this ,
class CategoryItems extends Component {
constructor(props) {
super(props);
}
state = {
items: this.props.items,
categories: this.props.categories,
};
render() {
const items = this.state.items;
const renderList = this.state.categories.reduce((total, category) => {
const list = items.filter(item => item.Category === category.Name);
if(list.length > 0){
total.push(<CategoryItem
key={category.Name}
items={list}
/>);
}
return total
},[])
return (
<section className="category-wrapper">
<div className="container">
<div className="category-wrapper__inner">
{renderList}
</div>
</div>
</section>
);
}
}

Rendering a nested object state

This problem is giving me a huge headache so any help is welcome :)
In this component, I'm making 2 axios calls to different APIs: one for freegeoip and one for openweathermap. I'm storing the data in the currentCity state, which is an object with 2 keys, location and weather. The idea is that the app detects your current location (using freegeoip) and renders location name and weather data (using openweathermap).
I'm positive it's storing the state properly as console logs have confirmed. I can render the location data for currentCity state, but can't seem to render the weather data for currentCity state.
renderCurrentCity(city) {
console.log('state3:', this.state.currentCity);
console.log([city.weather.main]);
return(
<div>
<li>{city.location.city}, {city.location.country_name}</li> // Working
<li>{city.weather.main.temp}</li> // Not working
</div>
)
}
The console error I get:
Uncaught (in promise) TypeError: Cannot read property '_currentElement' of null
currentCity.location JSON:
{
"ip": // hidden,
"country_code": "FR",
"country_name": "France",
"region_code": "GES",
"region_name": "Grand-Est",
"city": "Reims",
"zip_code": "",
"time_zone": "Europe/Paris",
"latitude": 49.25,
"longitude": 4.0333,
"metro_code": 0
}
currentCity.weather JSON:
{
"coord": {
"lon": 4.03,
"lat": 49.25
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 283.15,
"pressure": 1011,
"humidity": 43,
"temp_min": 283.15,
"temp_max": 283.15
},
"visibility": 10000,
"wind": {
"speed": 3.1,
"deg": 350
},
"clouds": {
"all": 0
},
"dt": 1493127000,
"sys": {
"type": 1,
"id": 5604,
"message": 0.1534,
"country": "FR",
"sunrise": 1493094714,
"sunset": 1493146351
},
"id": 2984114,
"name": "Reims",
"cod": 200
}
Rest of code:
import React, { Component } from 'react';
import axios from 'axios';
import WeatherList from './weatherlist';
import SearchBar from './searchbar';
const API_KEY = '95108d63b7f0cf597d80c6d17c8010e0';
const ROOT_URL = 'http://api.openweathermap.org/data/2.5/weather?'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
cities: [],
errors: '',
currentCity: {
location: {},
weather: {}
}
};
this.currentCity();
this.renderCurrentCity = this.renderCurrentCity.bind(this);
}
citySearch(city) {
const url = `${ROOT_URL}&appid=${API_KEY}&q=${city}`;
axios.get(url)
.then(response => {
const citiesArr = this.state.cities.slice();
this.setState({
cities: [response.data, ...citiesArr],
errors: null
});
})
.catch(error => {
this.setState({
errors: 'City not found'
})
})
}
currentCity() {
var city;
var country;
axios.get('http://freegeoip.net/json/')
.then(response => {
const lat = response.data.latitude;
const lon = response.data.longitude;
city = response.data.city;
country = response.data.country_name;
const url = `${ROOT_URL}&appid=${API_KEY}&lat=${lat}&lon=${lon}`;
const state = this.state.currentCity;
console.log('state1:',state);
this.setState({
currentCity: { ...state, location: response.data }
});
console.log(url);
axios.get(url)
.then(city => {
const state = this.state.currentCity;
console.log('state2:', state);
this.setState({
currentCity: { ...state, weather: city.data }
});
})
})
}
renderCurrentCity(city) {
console.log('state3:', this.state.currentCity);
console.log([city.weather.main]);
return(
<div>
<li>{city.location.city}, {city.location.country_name}</li>
<li>{city.weather.main.temp}</li>
</div>
)
}
render() {
return (
<div className={this.state.cities == false ? 'search': 'search-up'}>
<h1>What's the weather today?</h1>
<ul className='list-unstyled text-center'>
{this.renderCurrentCity(this.state.currentCity)}
</ul>
<SearchBar
onSearchSubmit={this.citySearch.bind(this)}
errors={this.state.errors} />
{this.state.cities == false ? null : <WeatherList cities={this.state.cities} />}
</div>
)
}
}
You are spreading your whole state when your receive the weather data:
this.setState({
currentCity: { ...state, weather: city.data }
});
it should be:
this.setState({
currentCity: { ...state.currentCity, weather: city.data }
});

Resources