how to fetch nested api data in ReactJS? - javascript

i am trying to solve this problem is, whenever user will click on category title then user will redirect to another page and will see the product_set data as per category id or slug.
i am probably new to ReactJs, it would be great if anybody could help me out what i am trying to solve is. thank you so much in advance.
end point url: "http://localhost:8000/api/p_category"
Api data:
[
{
"id": 1,
"title": "category01",
"slug": "category01",
"description": "",
"image": "http://localhost:8000/media/cat2_KpMV1YQ.jpg",
"product_set": [
{
"url": "http://localhost:8000/api/p/product01",
"id": 1,
"title": "product01",
"slug": "product01",
"image": "http://localhost:8000/media/product2_EMWEgQI.png",
"price": 5,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
},
]
},
{
"id": 3,
"title": "category03",
"slug": "category03",
"description": "category03 desc..",
"image": "http://localhost:8000/media/cat3_9dal1uP.jpg",
"product_set": [
{
"url": "http://localhost:8000/api/p/product03",
"id": 3,
"title": "product03",
"slug": "product03",
"image": "http://localhost:8000/media/product5.png",
"price": 3,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
},
{
"url": "http://localhost:8000/api/p/product06",
"id": 5,
"title": "product06",
"slug": "product06",
"image": "http://localhost:8000/media/product6_rkmAlce.png",
"price": 12,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
}
]
}
]

You can do like this,
import { React } from "react";
class categoryListExample extends React.Component{
state={
categoryList:[],
category:''
}
async componentDidMount(){
let res=await fetch("http://localhost:8000/api/p_category")
//assuming you are getting data in response.data
this.setState({categoryList:res.data})
}
categoryChangeHandler=(category)=>{
this.setState({category})
}
render(){
const {categoryList,category}=this.state
if (categoryList.length>0) {
return(
<div>
<ul>
{categoryList.map(category=><li key={category.id} onClick={this.categoryChangeHandler}>{category.title}</li>)}
</ul>
<CategoryComponent category={category.product_set}/>
</div>
)
} else {
return(
<div>
Loading...
</div>
)
}
}
}
export default categoryListExample;

Related

Uncaught TypeError: Cannot read properties of undefined (reading 'name')

Here is my code
This is Service.js file
import React, { useEffect, useState } from 'react';
import Home from './Home';
const Service = () => {
const [products, setProducts] = useState([]);
useEffect( ()=>{
fetch('data.json')
.then(res => res.json())
.then(data => setProducts(data))
}, [])
return (
<div>
{
products.map(product => <Home product={product}></Home>)
}
</div>
);
};
export default Service;
Where I want to send data
import React from 'react';
const Home = (props) => {
const {name, img, extra} = props.product;
return (
<div>
<h1>Name: {name} </h1>
</div>
);
};
export default Home;
Database
[
{
"id": 1,
"extra": "mahfuzur",
"name": "Professor Dr. Md. Mahfuzur Rahman",
"title": "Dean, Faculty of Engineering & Technology",
"mobile": "09602666651 09602666652",
"email": "dean_et#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FChairperson.jpg"
},
{
"id": 2,
"name": "Prof. Dr. Engr. Aminul Hoque",
"extra": "aminul Hoque",
"title": "Professor",
"mobile": "09602666651, 09602666652",
"email": "ahoque.eee#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FAminulHoque.jpg"
},
{
"id": 3,
"extra": "golam robbani",
"name": "Professor Dr. Mirza Golam Rabbani",
"title": "Chairperson, Department of Electrical & Electronic Engineering",
"mobile": "09602666651, 09602666652 ",
"email": "mgrabbani#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FRabbaniChairperson_EEE.jpg"
},
{
"id": 4,
"extra": "mahfuz",
"name": "Mr. Muhammad Mahfuz Hasan",
"title": "Chairperson and Assistant Professor, Department of Computer Science and Engineering",
"mobile": "9602666651, 09602666652",
"email": "mhasan#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FMilonSir.jpg"
},
{
"id": 5,
"extra": "iqbal mahmud",
"name": "Dr. Iqbal Mahmud",
"title": "Assistant Professor and Hostel Super (Male Hostel)",
"mobile": "0909602666651, 09602666652",
"email": "iqbal.et#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FIqbal.et.jpg"
},
{
"id": 6,
"extra": "nargis begam",
"name": "Ms. Nargis Begam",
"title": "Lab Manager(Technical)",
"mobile": "09602666651, 09602666652",
"email": "nargis#easternuni.edu.bd",
"img": "https://www.easternuni.edu.bd/assets/Admins%2FOffice_New%2FNargis.jpg"
}
]
I fetch the data and I send it via product={product}in home section where I want to send. But when I send the data Home section didn't find any data. Is there any possibility of compiler error? or what is the main problem I didn't catch? Please help me.

Extracting info from object REACT

I have this object:
{
"id": 24,
"pic": {
"pic": [{
"url": "760634d2-f8ec-4caa-9a2d-14a8828cfb5dpetplace.jpg"
},
{
"url": "760634d2-f8ec-4caa-9a2d-14a8828cfb5dpetplace.jpg"
}
]
},
"title": "Title",
"title_icon": "760634d2-f8ec-4caa-9a2d-14a8828cfb5dpetplace.jpg",
"social_link": {
"social_link": [{
"facebook": "https://facebook.com"
},
{
"instagram": "https://insta.com"
}
]
},
"phone_number": "03246101715",
"address": "346-B PUEHS TOWN 1 BLOCK B",
"lat": "45678",
"long": "45678",
"postcode": "54000",
"start_time": "2021-11-15T12:15:39.658Z",
"end_time": "2021-11-15T12:15:39.658Z",
"email": "Husnain#gmail.com",
"web_url": "https://getbootstrap.com",
"createdAt": "2021-11-15T12:15:39.658Z",
"category": {
"id": 1,
"name": "Resturant",
"pic": "restaurent.png",
"createdAt": "2021-11-16T18:56:51.163Z"
}
},
I want too return the facebook and insta links in a table. I am using a map function to display all the records since there are multiple objects in the array.
{
filteredData.map((product) => (
<Fragment>
{editContactId === product.id ? (
<EditableData data={product} />
) : (
<ReadOnly
data={product}
id={product.id}
handleEditClick={handleEditClick}
/>
)}
</Fragment>
));
}
I have tried this <td>{data.social_link.social_link[0].facebook}</td> but it does not work. Any suggestions?

Error querying by string in nodejs api rest

I'm actually creating an app for my neighborhood little business, y have this db schema using Postgresql:
https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_schema_db_dykxnt.png
my use cases are:
1 user can create 1 experience.
1 user can create a business local only if its going to leave an experience from it.
1 experience can have several images.
( I haven't a relationship between business_locals and users because doesn't matter for who creates the business).
I haven't had problems untill now, I'm trying to get the business with it's name, lat and lng; the average score given by users, 1 image from the last experience where the name like = "somestring"
this are my models:
Business Model: https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_businessmd_rwnsnu.png
Images model: https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_imgaesmd_m4hkzv.png
experiencies model: https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_experienciesmd_f7jtxt.png
y try this code:
export async function getBusinessByQueryString(req, res) {
let query = req.params.query;
const businessesResult = await Business.findAll({
where: Sequelize.where(
Sequelize.fn("LOWER", Sequelize.col("name")),
{
[Op.like]: `%${query}%`
}
),
attributes: ['name', sequelize.fn('COUNT', sequelize.col('experiencies.id'))],
include: [
{ model: Experiencies, attributes: [] }
],
group: ["business_locals.id"]
}).catch(err => {
return res.status(500).json({
ok: false,
messagge: "Error al consultar el comercio",
err
});
});
console.log(businessesResult);
// let businessIdArrays = businessesResult.map((obj) => obj.id);
// console.log(businessIdArrays);
return res.json({
ok: true,
message: businessesResult
});
}
but I'm having this error:
https://res.cloudinary.com/dthhugesg/image/upload/v1569939691/nodejserror/error_x0tsiq.png
I'm expecting this:
[
{
"id": 2,
"name": "Business local example 1",
"lat": 6.24523,
"lng": -75.4543,
"average_score": 4,
"experiences": [
{
"id": 1,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [
{
"url": "https://placeimg.com/640/490/tech"
},
{
"url": "https://placeimg.com/640/490/animals"
}
],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 1,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [
{
"url": "https://placeimg.com/640/490/tech"
},
{
"url": "https://placeimg.com/640/490/animals"
}
],
"user": {
"id": 2,
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 2,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 3,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 4,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
}
]
},
{
"id": 3,
"name": "Business local example 2",
"lat": 6.24523,
"lng": -75.4543,
"average_score": 4,
"experiences": [
{
"id": 1,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [
{
"url": "https://placeimg.com/640/490/animals"
}
],
"user": {
"id": 2,
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 4,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
}
]
}
]
thank you very much, all of you i hope that someone can help me and tell me if i have any mistake

How to loop through nested JSON and append in HTML DOM

I am trying to loop through a JSON and append it to HTML in a nested way. What I am trying to do is add a Header tag for the title of the object and have tags for the titles of items. Some objects might not have the items as empty too. I am guessing a nested loop is required and I've tried implementing it. The JSON looks like:
[
{
"id": 1,
"title": "Hello",
"url": "http://localhost:8000/login/notes/1/",
"description": "Hello nice",
"created_at": "2019-08-10T06:02:55.468315Z",
"created_by": "Dude",
"items": [
{
"id": 1,
"url": "http://localhost:8000/login/items/1/",
"title": "baby's toy",
"note": "http://localhost:8000/login/notes/1/"
},
{
"id": 2,
"url": "http://localhost:8000/login/items/2/",
"title": "baby's toy",
"note": "http://localhost:8000/login/notes/1/"
},
{
"id": 4,
"url": "http://localhost:8000/login/items/4/",
"title": "postman5",
"note": "http://localhost:8000/login/notes/1/"
}
]
},
{
"id": 2,
"title": "abc",
"url": "http://localhost:8000/login/notes/2/",
"description": "asad",
"created_at": "2019-08-10T15:23:53.074848Z",
"created_by": "dude2",
"items": [
{
"id": 5,
"url": "http://localhost:8000/login/items/5/",
"title": "Parrot Toy",
"note": "http://localhost:8000/login/notes/2/"
}
]
}]
I've tried
fetch('http://localhost:8000/login/notes/?format=json',{mode: 'cors'})
.then(response => response.json())
.then(data => {
var output='';
var final='';
var semif='';
var darif='';
for (var i in data) {
output+=i+'<h2>'+data[i].title +'</h2>'
for(j in data[i].items){
final+='<li>'+data[i].items[j].title+'</li>'
}
semif=output+final
}
document.getElementById('test').innerHTML=darif
});
HTML
<p id="test">
</p>
What I want to achieve is:
<h1>Hello</h1>
<h5>baby's toy</h5>
<h5>baby's toy</h5>
<h5>postman5</h5>
<h1>abc</h1>
<h5>parrot's toy</h5>
I strongly advise against doing lengthy string concatenations. Strings are immutable objects and they can put unnecessary burden on your system.
In addition, using map and join is much more elegant and easier to read.
const data = [
{
"id": 1,
"title": "Hello",
"url": "http://localhost:8000/login/notes/1/",
"description": "Hello nice",
"created_at": "2019-08-10T06:02:55.468315Z",
"created_by": "Dude",
"items": [
{
"id": 1,
"url": "http://localhost:8000/login/items/1/",
"title": "baby's toy",
"note": "http://localhost:8000/login/notes/1/"
},
{
"id": 2,
"url": "http://localhost:8000/login/items/2/",
"title": "baby's toy",
"note": "http://localhost:8000/login/notes/1/"
},
{
"id": 4,
"url": "http://localhost:8000/login/items/4/",
"title": "postman5",
"note": "http://localhost:8000/login/notes/1/"
}
]
},
{
"id": 2,
"title": "abc",
"url": "http://localhost:8000/login/notes/2/",
"description": "asad",
"created_at": "2019-08-10T15:23:53.074848Z",
"created_by": "dude2",
"items": [
{
"id": 5,
"url": "http://localhost:8000/login/items/5/",
"title": "Parrot Toy",
"note": "http://localhost:8000/login/notes/2/"
}
]
}]
const result = data.map(el => {
return `<h1>${el.title}</h1>` + el.items.map(el => `<h5>${el.title}</h5>`).join("")
}).join("")
console.log(result)
fetch('http://localhost:8000/login/notes/?format=json',{mode: 'cors'})
.then(response => response.json())
.then(data => {
var html = '';
data.forEach(listItem => {
const h1 = `<h1> ${listItem.title} </h1>`;
html+=h1;
listItem.items.forEach(item=> {
const h5 = `<h5> ${item.title} </h5>`;
html+=h5;
});
});
document.getElementById('test').innerHTML=html;
});
I think you may use it.

iterate over JSON in react native

I've come across a problem working in react native. I've parsed a large JSON object and need to iterate over an array nested inside it. All I need to do is print three values in each item object for day[0].
My code:
import React, { Component, PropTypes } from 'react';
import { View, Text, ListView, StyleSheet, TouchableHighlight} from 'react-native';
import Header from '../Components/Header';
import Api from '../Utility/Api';
export default class CalendarPage extends Component {
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(
fetch('https://s3.amazonaws.com/cbu-rec-center-app/credentials/schedule.json')
)
};
}
componentWillMount(){
Api.getDates().then((res) => {
this.setState({
//I need to have these three output, but for all items in day[0]
EventName: res.days[0].items[0].summary,
EventDate: res.days[0].items[0].start.dateTime,
EventLocation: res.days[0].items[0].description
})
})
}
render() {
return (
<View style={{flex: 1}}>
<Header pageName="Calendar" navigator={this.props.navigator}/>
<View style = {{flex:9}}>
<Text> {this.state.EventName} </Text>
<Text> {this.state.EventDate} </Text>
<Text> {this.state.EventLocation} </Text>
</View>
</View>
);
}
}
The JSON
"days": [{
"date": "2017-03-06",
"hours": {
"open": "06:00",
"close": "12:00"
},
"items": [{
"kind": "calendar#event",
"etag": "\"2977101842476000\"",
"id": "fhq5hof67nvqhj85qm65t1n3e4",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=ZmhxNWhvZjY3bnZxaGo4NXFtNjV0MW4zZTQgY2J1cmVjcmVhdGlvbmNlbnRlckBt",
"created": "2017-03-03T14:22:01.000Z",
"updated": "2017-03-03T14:22:01.238Z",
"summary": "Women's Volleyball",
"description": "West Court",
"creator": {
"email": "cburecreationcenter#gmail.com",
"displayName": "Cbu RecreationCenter",
"self": true
},
"organizer": {
"email": "cburecreationcenter#gmail.com",
"displayName": "Cbu RecreationCenter",
"self": true
},
"start": {
"dateTime": "2017-03-06T15:30:00-08:00"
},
"end": {
"dateTime": "2017-03-06T16:30:00-08:00"
},
"iCalUID": "fhq5hof67nvqhj85qm65t1n3e4#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"type": "event"
},
{
"kind": "calendar#event",
"etag": "\"2976616094232000\"",
"id": "4tnn4gn0gstndi5idrqjsg7elo_20170306T200000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=NHRubjRnbjBnc3RuZGk1aWRycWpzZzdlbG9fMjAxNzAzMDZUMjAwMDAwWiBrbTVyM2dycW1qbjZiMTQ2MWk2aXBjMjJhc0Bn",
"created": "2017-02-28T14:24:06.000Z",
"updated": "2017-02-28T18:54:07.116Z",
"summary": "Boxing Boot Camp",
"creator": {
"email": "cburecreationcenter#gmail.com",
"displayName": "Cbu RecreationCenter"
},
"organizer": {
"email": "km5r3grqmjn6b1461i6ipc22as#group.calendar.google.com",
"displayName": "Group X Calendar",
"self": true
},
"start": {
"dateTime": "2017-03-06T12:00:00-08:00"
},
"end": {
"dateTime": "2017-03-06T12:45:00-08:00"
},
"recurringEventId": "4tnn4gn0gstndi5idrqjsg7elo",
"originalStartTime": {
"dateTime": "2017-03-06T12:00:00-08:00"
},
"iCalUID": "4tnn4gn0gstndi5idrqjsg7elo#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"type": "class"
},
{
"kind": "calendar#event",
"etag": "\"2967485504076000\"",
"id": "m533eg9bu5o4meinuu7pvfoge4_20170306T210000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=bTUzM2VnOWJ1NW80bWVpbnV1N3B2Zm9nZTRfMjAxNzAzMDZUMjEwMDAwWiBrbTVyM2dycW1qbjZiMTQ2MWk2aXBjMjJhc0Bn",
"created": "2017-01-06T22:45:52.000Z",
"updated": "2017-01-06T22:45:52.038Z",
"summary": "Women on Weights",
"description": "This is a weight lifting class designed to empower women to lift free weights in a group setting . The goals of WOW are to teach proper form, assist women in improving their posture, increasing their strength, and muscle pairing. ",
"location": "Group X Room",
"creator": {
"email": "cburecreationcenter#gmail.com",
"displayName": "Cbu RecreationCenter"
},
"organizer": {
"email": "km5r3grqmjn6b1461i6ipc22as#group.calendar.google.com",
"displayName": "Group X Calendar",
"self": true
},
"start": {
"dateTime": "2017-03-06T13:00:00-08:00",
"timeZone": "America/Los_Angeles"
},
"end": {
"dateTime": "2017-03-06T14:00:00-08:00",
"timeZone": "America/Los_Angeles"
},
"recurringEventId": "m533eg9bu5o4meinuu7pvfoge4",
"originalStartTime": {
"dateTime": "2017-03-06T13:00:00-08:00",
"timeZone": "America/Los_Angeles"
},
"iCalUID": "m533eg9bu5o4meinuu7pvfoge4#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"type": "class"
},
you can do it using .map():
<View>
{ res.days[0].items.map((item) => (
<View>
<Text>{item.summary}</Text>
<Text>{item.start.dateTime}</Text>
<Text>{item.description}</Text>
</View>
))}
</View>
make sure to check for data availability not to display empty <Text> blocks

Categories

Resources