Am getting data from the back end(api) but i cannot display it to the view.
i have tried several solutions but diddn't seem to work.
<ul>
<li *ngFor="let item of data">
<h4>{{item.address}}</h4>
<h4>{{item.city}}</h4>
</li>
</ul>
the data is pasted below. I used JSON.stringify() to convert the data from object to string and stored it in a variable getEventData. when i do interpolation of the results like this {{getEventData}} it comes alright but cannot format it.
thanks in advance.
//get request to api
this._http.get( this.url + param, {headers:headers})
.map((res:Response) => res.json())
.subscribe(
data => this.getEventData = JSON.stringify(data),
error =>this.logError(error),
() => console.log('get request completed sucesfully')
);
data from api
{
"data": [
{
"address": "Great 22",
"banner_image": null,
"city": "Kum",
"country": "",
"creator_id": 15,
"description": "50th congregation",
"end_time": "2016-07-05T15:30:00+00:00",
"event_id": 5,
"is_online": false,
"max_tickets_per_user": 1,
"show_id": 7,
"start_time": "2016-07-05T09:00:00+00:00",
"state": "Ash",
"title": "Graduation",
"venue": "Great Hall"
},
{
"address": "CCB Auditorium",
"banner_image": null,
"city": "Kumasi",
"country": "hema",
"creator_id": 15,
"description": "school graduation",
"end_time": "2016-07-06T15:30:00+00:00",
"event_id": 5,
"is_online": false,
"max_tickets_per_user": 1,
"show_id": 8,
"start_time": "2016-07-06T09:00:00+00:00",
"state": "hama",
"title": "Graduation",
"venue": "CCB Auditorium"
},
{
"address": "Engineering Auditorium",
"banner_image": null,
"city": "Kumasi",
"country": "Ghana",
"creator_id": 15,
"description": "KNUST graduation for the 50th congregation",
"end_time": "2016-07-06T15:30:00+00:00",
"event_id": 5,
"is_online": false,
"max_tickets_per_user": 1,
"show_id": 9,
"start_time": "2016-07-06T09:00:00+00:00",
"state": "Ash",
"title": "Graduation",
"venue": "Engineering Auditorium"
}
]
}
You don't need JSON.stringify if you plan to render data with *ngFor:
.subscribe(
data => this.getEventData = data.data, // note extra .data
error => this.logError(error),
() => console.log('get request completed succesfully')
);
Related
So I can call the variable "teams" and see the data fine but I can't get the values from it in my {#each} block. I know its not part of the "fixtures" variable I'm iterating through and tbh that's probably the issue.
Does anyone know how I can get the actual values within "teams" instead of getting 'undefined' or a better way of fetching multiple arrays within themselves? (ill put the example at the bottom)
my +page.svelte
<script>
export let data;
const { fixtures } = data;
const teams = fixtures.flatMap(fixtures => fixtures.participants)
console.log(teams)
</script>
<div class="flex flex-col absolute top-[0] right-0 w-[85vw] p-6">
<div class="">
{#each fixtures as fixture}
<p>{fixture.name}</p>
<div class="">{fixture.home_score}{fixture.away_score}</div>
<p>{teams.short_code}</p>
{/each}
</div>
</div>
+page.server.js
export const load = async () => {
const fetchList= async () => {
const url = `https://api.sportmonks.com/v3/football/schedules/seasons/19734?api_token=${process.env.API_KEY}`;
const res = await fetch(url);
const data = await res.json()
return data.data.flatMap(data => data.rounds.map(rounds => rounds.fixtures)).flat()
}
return {
fixtures: fetchList(),
}
}
The API
{
"data": [
{
"id": 77457864,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"type_id": 223,
"name": "Regular Season",
"sort_order": 1,
"finished": false,
"is_current": true,
"starting_at": "2022-08-05",
"ending_at": "2023-05-28",
"rounds": [
{
"id": 274668,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"stage_id": 77457864,
"name": "1",
"finished": true,
"is_current": false,
"starting_at": "2022-08-05",
"ending_at": "2022-08-07",
"fixtures": [
{
"id": 18535049,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"stage_id": 77457864,
"group_id": null,
"aggregate_id": null,
"round_id": 274668,
"state_id": 5,
"venue_id": 206,
"name": "Manchester United vs Brighton & Hove Albion",
"home_score": 1,
"away_score": 2,
"starting_at": "2022-08-07 13:00:00",
"result_info": "Brighton & Hove Albion won after full-time.",
"leg": "1/1",
"details": null,
"length": 90,
"placeholder": false,
"last_processed_at": "2022-12-05 09:15:37",
"starting_at_timestamp": 1659877200,
"participants": [
{
"id": 14,
"sport_id": 1,
"country_id": 462,
"venue_id": 206,
"gender": "male",
"name": "Manchester United",
"short_code": "MUN",
"image_path": "https://cdn.sportmonks.com/images/soccer/teams/14/14.png",
"founded": 1878,
"type": "domestic",
"placeholder": false,
"last_played_at": "2022-12-10 17:00:00",
"meta": {
"location": "home"
}
},
{
"id": 78,
"sport_id": 1,
"country_id": 462,
"venue_id": 480,
"gender": "male",
"name": "Brighton & Hove Albion",
"short_code": "BRH",
"image_path": "https://cdn.sportmonks.com/images/soccer/teams/14/78.png",
"founded": 1901,
"type": "domestic",
"placeholder": false,
"last_played_at": "2022-12-08 13:00:00",
"meta": {
"location": "away"
}
}
]
},
There's a "dirty" way to do it with {#key}
I am facing problem in getting values from rendered data in component that is already outputted on page render. What I need to do is, when someone types in data into text field, it should send it to database but taking that fields data from runtime data.
Currently, when I type something, it says undefined field etc.
This is not form data but a data that need to be update from text field.
So, if user write some xyz in text field, we need to update that data according to the id associated to that field.
I am not able to get data into: console.log(Id, projectId, userId, date, e.target.value)
I have used reduce method that serves the purpose but now I have another use case.
I dont want to set hidden fields as its not the right approach.
The problem is that when someone type data in text field, I need to get that text field data and associated id and respective data from it and pass it ti ajax call.
I need to send that data with ajax but as soon as I type something, it says undefined. I can easily get data from projects array but its of no use to me. I think array reduce method is not good for my use case.
Here is project array:
data = [
{
"id": 27,
"projectno": "007823",
"projectname": "non-A Project 2",
"dailyproof": 1,
"probability": "1.0",
"toleranceregistering": 2,
"customer_name": "Peter",
"user_id": "4",
"days_allocated": "231.0",
"days_real": "5.0",
"hours_real": "6.0",
"project_times": [
{
"id": 11,
"activity": "\"yht\"",
"date": "2020-04-28",
"hours": "2.0",
"project_id": 27,
"token": "\"trr\"",
"user_id": 4,
"created_at": "2020-04-22T12:36:55.479Z",
"updated_at": "2020-04-22T12:36:55.479Z"
},
{
"id": 12,
"activity": "\"yht\"",
"date": "2020-04-03",
"hours": "2.0",
"project_id": 27,
"token": "\"trr\"",
"user_id": 4,
"created_at": "2020-04-22T12:37:08.763Z",
"updated_at": "2020-04-22T12:37:08.763Z"
},
{
"id": 13,
"activity": "\"yht\"",
"date": "2020-04-14",
"hours": "2.0",
"project_id": 27,
"token": "\"dfg\"",
"user_id": 4,
"created_at": "2020-04-22T12:37:19.177Z",
"updated_at": "2020-04-22T12:37:19.177Z"
}
]
},
{
"id": 28,
"projectno": "007333",
"projectname": "non-A Project 2",
"dailyproof": 0,
"probability": "1.0",
"toleranceregistering": 2,
"customer_name": "Peter",
"user_id": "4",
"days_allocated": "231.0",
"days_real": "3.333333333333333333333333334",
"hours_real": "4.0",
"project_times": [
{
"id": 18,
"activity": "\"tgr\"",
"date": "2020-04-16",
"hours": "2.0",
"project_id": 28,
"token": "\"ujy\"",
"user_id": 4,
"created_at": "2020-04-22T12:39:41.465Z",
"updated_at": "2020-04-22T12:39:41.465Z"
},
{
"id": 19,
"activity": "\"ddd\"",
"date": "2020-04-11",
"hours": "2.0",
"project_id": 28,
"token": "\"fff\"",
"user_id": 4,
"created_at": "2020-04-22T12:39:55.020Z",
"updated_at": "2020-04-22T12:39:55.020Z"
}
]
},
{
"id": 29,
"projectno": "00721",
"projectname": "non-A Project 2",
"dailyproof": 1,
"probability": "1.0",
"toleranceregistering": 2,
"customer_name": "Peter",
"user_id": "4",
"days_allocated": "231.0",
"days_real": "5.0",
"hours_real": "6.0",
"project_times": [
{
"id": 22,
"activity": "\"cdf\"",
"date": "2020-04-11",
"hours": "2.0",
"project_id": 29,
"token": "\"fgff\"",
"user_id": 4,
"created_at": "2020-04-22T12:41:26.392Z",
"updated_at": "2020-04-22T12:41:26.392Z"
},
{
"id": 23,
"activity": "\"tg\"",
"date": "2020-04-15",
"hours": "2.0",
"project_id": 29,
"token": "\"ad\"",
"user_id": 4,
"created_at": "2020-04-22T12:41:38.747Z",
"updated_at": "2020-04-22T12:41:38.747Z"
},
{
"id": 24,
"activity": "\"ff\"",
"date": "2020-04-19",
"hours": "2.0",
"project_id": 29,
"token": "\"bbb\"",
"user_id": 4,
"created_at": "2020-04-22T12:41:47.500Z",
"updated_at": "2020-04-22T12:41:47.500Z"
}
]
},
{
"id": 30,
"projectno": "0074",
"projectname": "non-A Project 2",
"dailyproof": 1,
"probability": "1.0",
"toleranceregistering": 2,
"customer_name": "Peter",
"user_id": "4",
"days_allocated": "231.0",
"days_real": "3.333333333333333333333333334",
"hours_real": "4.0",
"project_times": [
{
"id": 25,
"activity": "\"ff\"",
"date": "2020-04-12",
"hours": "2.0",
"project_id": 30,
"token": "\"bbb\"",
"user_id": 4,
"created_at": "2020-04-22T12:42:09.385Z",
"updated_at": "2020-04-22T12:42:09.385Z"
},
{
"id": 26,
"activity": "\"rter\"",
"date": "2020-04-19",
"hours": "2.0",
"project_id": 30,
"token": "\"gfdg\"",
"user_id": 4,
"created_at": "2020-04-22T12:42:19.861Z",
"updated_at": "2020-04-22T12:42:19.861Z"
}
]
}
]
getDaysNumber('2020', '04') {
const dayNums = [];
const daysInMonth = new Date(year, month, 0).getDate();
for (let i = 1; i <= daysInMonth; i++) {
dayNums.push(i);
// console.log(i, ' xxx ');
}
return dayNums;
}
{
data.map((h, index) => (
<TableRow key={`mi-${index}`}>
<TableCell align="right">{h.projectno}</TableCell>
<TableCell align="right">{h.projectname}</TableCell>
<TableCell align="right">{h.customer_name}</TableCell>
<TableCell align="right">{h.days_allocated}</TableCell>
<TableCell align="right">{h.days_real}</TableCell>
<TableCell align="right">{h.hours_real}</TableCell>
{daysNumber.reduce((acc, number, index) => {
const found = h.project_times.find(item => number == item["date"].split('-')[2].replace(/^0+/, ''))
const Id = found && found["id"];
const projectId = found && found["project_id"];
const userId = found && found["user_id"];
const date = found && found["date"];
const hours = found && found["hours"];
found && console.log(Id, projectId, userId, date);
return [...acc,
h.dailyproof == 1 && hours > 0.0 ?
<TableCell align="right" key={`mi-${index}`}
onClick={this.launchCreateContactDialog}>{hours}</TableCell>
:
<TableCell align="right" key={`mi-${index}`}>
<TextField required fullWidth size="small"
variant="outlined"
onKeyUp={(e) => console.log(Id, projectId, userId, date, e.target.value)}/>
</TableCell>
]
}, [])
}
</TableRow>
))
}
This find call may sometimes return undefined.
const found = h.project_times.find(item => number == item["date"]
.split('-')[2]
.replace(/^0+/, '')
)
This is expected when no matches are found. And since it's undefined, all of these will also end up undefined:
const Id = found && found["id"];
const projectId = found && found["project_id"];
const userId = found && found["user_id"];
const date = found && found["date"];
const hours = found && found["hours"];
Therefore, it's not unusual that your console.log statement will log out the value undefined.
It sounds like you're needing to do a few things:
Maintain this data as state in your component.
Add a function to mutate this state.
Add a function to store the state (calling an API)
I don't have enough context to answer #3 for you, but here's the type of pattern you want to go for:
import { useEffect, useState } from 'react';
function HoursEntry() {
const [state, setState] = useState();
useEffect(() => {
// Do your data fetching here; for now will use your constant
setState(data);
}, []);
function updateHours({ userId, projectId, hourEntryId, date, hours }) {
// Build newData based on the changes...
setState(newData);
}
// All the rendering stuff. Rendered components should be mappings of what's in
// state...
<TextField
required fullWidth
size="small"
variant="outlined"
value={hours}
onChange={(e) => updateHours({
userId,
projectId,
hourEntryId: Id,
date,
hours: parseFloat(e.target.value)
})}/>
// ...
}
Inside of your updateHours function, you'll create a new copy of your data with the expected modifications. For example, if you're updating an existing object, you'll update its hours property. If you're updating something for which there is no record, you'll create a new one, etc. The key is your call to setState to update the data in your component.
Then, once you have your submit button or whatever method you've got to store, you'll reference this state for the latest copy of your data.
That's the general pattern for any kind of form entry component; it's an exercise in updating state.
I'm fairly new to React and I've been wrapping my head for the last hour trying to display the results of an API. I have an API returning this:
{
"data": [{
"address": "34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo",
"balance": 17568220019863
},
{
"address": "35hK24tcLEWcgNA4JxpvbkNkoAcDGqQPsP",
"balance": 15100113065160
},
{
"address": "385cR5DM96n1HvBDMzLHPYcw89fZAXULJP",
"balance": 11530490707099
},
{
"address": "3CgKHXR17eh2xCj2RGnHJHTDjPpqaNDgyT",
"balance": 11185824585401
},
{
"address": "37XuVSEpWW4trkfmvWzegTHQt7BdktSKUs",
"balance": 9450576862072
},
{
"address": "183hmJGRuTEi2YDCWy5iozY8rZtFwVgahM",
"balance": 8594734898577
},
{
"address": "1FeexV6bAHb8ybZjqQMjJrcCrHGW9sb6uF",
"balance": 7995720088144
},
{
"address": "3D2oetdNuZUqQHPJmcMDDHYoqkyNVsFk9r",
"balance": 7689310178244
}
],
"context": {
"code": 200,
"source": "A",
"time": 0.14749908447265625,
"limit": 10,
"offset": 0,
"rows": 10,
"pre_rows": 10,
"total_rows": 27974300,
"state": 601405,
"cache": {
"live": true,
"duration": 60,
"since": "2019-10-28 17:53:32",
"until": "2019-10-28 17:54:32",
"time": null
}
}
};
I am only interested in the address and the balance. Now, in my state I have a richList: {}, but I can't figure out how to copy the JSON data I'm interested in into the richList.
I have this so far but of course it doesn't work:
componentDidMount() {
fetch(apiRequest)
.then(response => response.json())
.then(data => {
console.log(data.data[0]["address"])
this.setState({
richList: data
})
})
}
I think I need to use the map function but I can't figure out how exactly.
I'd appreciate some help.
I'm trying to accessing a json child object which is not in an array. i've tried accessing it with my below script but its not working. i want to be able to access the menuCategory Object
JSON
[
{
"id": 67,
"name": "Wednesday Menu",
"serveDate": "2019-06-12 00:00:00",
"expiryDate": "2019-06-12 16:11:00",
"status": "APPROVED",
"isEnabled": true,
"meals": [
{
"id": 45,
"name": "Waakye, Gari and Wele",
"description": "A very well designed food for all kids",
"image": "",
"mealType": "LUNCH",
"unitPrice": 30,
"status": "ENABLED"
},
{
"id": 46,
"name": "Gari and Beans",
"description": "A very well designed food for all kidsss",
"image": "",
"mealType": "LUNCH",
"unitPrice": 12,
"status": "ENABLED"
}
],
"menuCategory": {
"id": 2,
"name": "hello"
}
}
]
JAVASCRIPT
callEditMenu(parent, content) {
this.modalService.open(content);
this.editMenuCategoryId = parent.menuCategory.id;
}
May be like
const parent = [{"id":67,"name":"Wednesday Menu","serveDate":"2019-06-12 00:00:00","expiryDate":"2019-06-12 16:11:00","status":"APPROVED","isEnabled":true,"meals":[{"id":45,"name":"Waakye, Gari and Wele","description":"A very well designed food for all kids","image":"","mealType":"LUNCH","unitPrice":30,"status":"ENABLED"},{"id":46,"name":"Gari and Beans","description":"A very well designed food for all kidsss","image":"","mealType":"LUNCH","unitPrice":12,"status":"ENABLED"}],"menuCategory":{"id":2,"name":"hello"}}]
console.log(parent[0].menuCategory.id);
If the parent argument in the callEditMenu function is referring to the JSON you included then try parent[0].menuCategory.id
let arr = [{"id":67,"name":"Wednesday Menu","serveDate":"2019-06-12 00:00:00","expiryDate":"2019-06-12 16:11:00","status":"APPROVED","isEnabled":true,"meals":[{"id":45,"name":"Waakye, Gari and Wele","description":"A very well designed food for all kids","image":"","mealType":"LUNCH","unitPrice":30,"status":"ENABLED"},{"id":46,"name":"Gari and Beans","description":"A very well designed food for all kidsss","image":"","mealType":"LUNCH","unitPrice":12,"status":"ENABLED"}],"menuCategory":{"id":2,"name":"hello"}}]
for (let item of arr) {
if (item.hasOwnProperty("menuCategory")) {
console.log(item["menuCategory"]);
}
};
let res = arr.filter((item) => item && item.menuCategory);
console.log(res[0].menuCategory);
In case you need to find it dynamically. Above are two different ways
Considering there would be multiple items in your array of objects, you can iterate through each object to get the menuCategory name as
let obj = [
{
"id": 67,
"name": "Wednesday Menu",
"serveDate": "2019-06-12 00:00:00",
"expiryDate": "2019-06-12 16:11:00",
"status": "APPROVED",
"isEnabled": true,
"meals": [
{
"id": 45,
"name": "Waakye, Gari and Wele",
"description": "A very well designed food for all kids",
"image": "",
"mealType": "LUNCH",
"unitPrice": 30,
"status": "ENABLED"
},
{
"id": 46,
"name": "Gari and Beans",
"description": "A very well designed food for all kidsss",
"image": "",
"mealType": "LUNCH",
"unitPrice": 12,
"status": "ENABLED"
}
],
"menuCategory": {
"id": 2,
"name": "hello"
}
}
];
obj.forEach(elem => {
console.log(elem.menuCategory.name);
});
I am new to realtime application and its bothering for a while how to render the data coming from websocket services like pusher using the angularjs ngRepeat directive..
below are the response from the api
and the snippets code i have.
Client Side.
$scope.exam_results = [{}];
var client = new Pusher('some_key');
var pusher = $pusher(client);
var my_channel = pusher.subscribe('some_channel');
my_channel.bind('some_event', function(data) {
$scope.some_var = data;
console.log($scope.some_var);
});
Server Side
.....
LaravelPusher::trigger($some_channel, 'some_event', $some_var);
By the way im using laravel and angularjs.
Need little help here guys.. thank you ^_^
Api Response
[
{
"id": 1,
"subject_id": 1,
"student_id": 1,
"correct": 0,
"incorrect": 30,
"created_at": "2016-02-17 17:47:36",
"updated_at": "-0001-11-30 00:00:00",
"exam_taken": 1,
"students": {
"id": 1,
"firstname": "Mary Rose",
"lastname": "Labrador",
"middlename": "Neneng",
"birthdate": "2016-02-10",
"email": "maryrose#dummy.com",
"username": "maryrose",
"gender": "Female",
"password": "65ce8ebfe1687cb8a5460fab48bcea413a0e17f53636912ac4667f056eeca461",
"guardianname": "Unnamed",
"guardiancontact": "+6309083561578",
"personalcontact": "+6309083561578",
"department_id": 1,
"taken_exam": 1,
"created_at": "2016-02-16 00:00:00",
"updated_at": "2016-02-17 17:47:58"
},
"subjects": {
"id": 1,
"subjectname": "Algorithm",
"slug": "algorithm",
"time": "10:00:00",
"schedule": "MWF",
"teacher_id": 1,
"created_at": "2016-02-12 09:28:27",
"updated_at": "2016-02-12 09:28:27"
}
},
{
"id": 2,
"subject_id": 1,
"student_id": 4,
"correct": 0,
"incorrect": 30,
"created_at": "2016-02-17 18:54:11",
"updated_at": "-0001-11-30 00:00:00",
"exam_taken": 1,
"students": {
"id": 4,
"firstname": "Joan Phylis",
"lastname": "Rogano",
"middlename": "Latoja",
"birthdate": "2016-02-14",
"email": "joangwapa#dummy.com",
"username": "joan143",
"gender": "Female",
"password": "65ce8ebfe1687cb8a5460fab48bcea413a0e17f53636912ac4667f056eeca461",
"guardianname": "Unnamed",
"guardiancontact": "+639083561578",
"personalcontact": "+639083561578",
"department_id": 1,
"taken_exam": 1,
"created_at": "2016-02-16 00:00:00",
"updated_at": "2016-02-17 18:57:43"
},
"subjects": {
"id": 1,
"subjectname": "Algorithm",
"slug": "algorithm",
"time": "10:00:00",
"schedule": "MWF",
"teacher_id": 1,
"created_at": "2016-02-12 09:28:27",
"updated_at": "2016-02-12 09:28:27"
}
}
]
HTML
<tr ng-reapeat="result in exam_results track by $index">
<td>
<span class="text-success">#{{result.students.lastname}},
#{{result.students.firstname}} #{{result.students.middlename}}
</span>
</td>
<td> View</td>
</tr>
As $scope.exam_results is an array, why not just use Array.concat() to add the new data to it? Angular's digest cycle would then render it:
$scope.exam_results = [];
// your websocket code
my_channel.bind('some_event', function(data) {
$scope.exam_results.concat(data);
console.log($scope.exam_results);
});
Obviously, the data from the websocket needs to be the same format over time and also an array of objects. You would bind your ng-repeat to $scope.exam_results.
<ul>
<li ng-repeat="result in exam_results track by $index">
{{result.students.firstname}}
</li>
</ul>
If your event data is consistently going to be an Array of Objects.
You can do something like this -
$scope.exam_results = []; // Changed this to Array.
var client = new Pusher('some_key');
var pusher = $pusher(client);
var my_channel = pusher.subscribe('some_channel');
my_channel.bind('some_event', function(data) {
$scope.exam_results.concat(data) // Concatinating Array to merge with existing Results.
});
Now you can have your view something like this -
<div ng-repeat="result in exam_results">
<!-- HTML to render Result -->
<span>{{result.students.first_name}}</span>
</div>
Hope this helps.