How to get complete response data based on text field entry Reactjs - javascript

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.

Related

Postman - Looping through an array of nested objects to make a variable

I am trying to set a variable from following phone number with value: “+33652556777” (index 4 in JSON attached below) which is the last object in contacts (index 4).
To do so is pretty simple:
let jsonData = pm.response.json();
console.log (jsonData.contacts[4].phone_numbers[0].value)
const PhoneNumber = jsonData.contacts[4].phone_numbers[0].value
pm.environment.set("Jacky", PhoneNumber);
Since I have to use different query parameters to filter by eg. created_at=asc, desc, the property of the phone_numbers order might change index number and I won’t be able to fetch desire phone number "+33652556777” instead it will set a different phone number which I cannot allow.
I know there is way to fetch our number and make it variable for next requests, which is iterating over properties or keys in the object “ for….in or for…of ” but for some reason I cannot achieve it.
What I could achieve is to get through first object “contacts” but impossible to get to its nested array “phone_numbers”. Here is how I did it:
let jsonData = pm.response.json();
let contact;
for (let filter of jsonData.contacts){
if (filter.last_name == "Rowland"){
contact = filter;
}}
console.log (contact);
Could you please help?
Here goes the JSON body response:
{
"contacts": [
{
"id": 11121211,
"direct_link": "https://example.example",
"first_name": "test1",
"last_name": "test",
"company_name": "test",
"information": null,
"is_shared": true,
"created_at": 1582798926,
"updated_at": 1582798926,
"emails": [],
"phone_numbers": [
{
"id": 60065270,
"label": "Work",
"value": "+33134567666"
}
]
},
{
"id": 22222222,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686067,
"updated_at": 1583686067,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567899"
}
]
},
{
"id": 33333564,
"direct_link": "https://example.example",
"first_name": "Jessica",
"last_name": "Biel",
"company_name": "N-Sync",
"information": null,
"is_shared": true,
"created_at": 1583686086,
"updated_at": 1583686086,
"emails": [],
"phone_numbers": []
},
{
"id": 45678901,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686105,
"updated_at": 1583686105,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567333"
}
]
},
{
"id": 56789123,
"direct_link": "https://example.example",
"first_name": "Jacky",
"last_name": "Rowland",
"company_name": "Test Company1",
"information": "",
"is_shared": true,
"created_at": 1583745888,
"updated_at": 1608556499,
"emails": [
{
"id": 76594398,
"label": "Work",
"value": "mandatory_field#example.com"
}
],
"phone_numbers": [
{
"id": 60650277,
"label": "Mobile",
"value": "+33652556777"
}
]
}
],
"meta": {
"count": 6,
"total": 241,
"current_page": 1,
"per_page": 5,
"next_page_link": "https://example.example",
"previous_page_link": null
}
}
You could use something basic like this:
_.each(pm.response.json().contacts, (contact) => {
if(contact.last_name === "Rowland") {
pm.environment.set(`${contact.first_name}_${contact.last_name}_number`, contact.phone_numbers[0].value)
}
})
There are probably better and more performant ways to do this but if you just want to set a variable for that contact, no matter where they are in the response - This would work :D
you can use forEach or _.each as danny mentioned to get all numbers else use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers[0].value)
use array.find to find the contact with first_name jacky adn then get phone_number[0].value from it.
if you want all numbers from that array then use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers.map((a)=>a.value))
here we map the result to get only the numbers from phone_number array.
is it what you looking for !?

React-Native remove object from Array

I'm trying to remove an object from the array, even though, I'm not sure how to grab the object, which basically makes the code that is written not make anything.
Let me show the existing array:
Object {
"created_at": "2020-06-30T11:22:53.000000Z",
"icon": "subjectImgs/509-1080x1080.jpg",
"id": 2,
"name": "Test",
"updated_at": "2020-06-30T11:22:53.000000Z",
"user_id": 1,
},
Object {
"created_at": "2020-06-04T18:32:25.000000Z",
"icon": "subjectImgs/698-1080x1080.jpg",
"id": 1,
"name": "history",
"updated_at": "2020-06-04T18:32:25.000000Z",
"user_id": 1,
},
Object {
"created_at": "2020-07-08T16:32:03.000000Z",
"icon": "subjectImgs/698-1080x1080.jpg",
"id": 21, // Here is the ID
"name": "123",
"updated_at": "2020-07-08T16:32:03.000000Z",
"user_id": 1,
},
}
When the event is listened to, I get the array of the object that was just deleted:
Object {
"socket": null,
"subject": Object {
"created_at": "2020-07-08T16:32:03.000000Z",
"icon": "subjectImgs/698-1080x1080.jpg",
"id": 21, // Here is the ID
"name": "123",
"updated_at": "2020-07-08T16:32:03.000000Z",
"user_id": 1,
},
}
Now, the way I'm trying to delete it is the following:
.listen('SubjectRemoved', ev => {
var array = this.state.subjects
this.setState({ subjects: array.filter((id) => id != ev.subject.id) })
});
but apparently, this is not working. I assume because of using id really gets nothing.
I think that the problem is in the filter method:
array.filter((id) => id != ev.subject.id) // here id is an elemt of the array not the real id
You could try
array.filter((subject) => subject.id != ev.subject.id) //if is an array of subjects
or
array.filter((elem) => elem.subject.id != ev.subject.id) //if is an array of objects like {socket: null, subject: {... with the fields }}
If you think that the ev.subject.id is not working you could just console.log it before the filter senetence.

JavaScript Mapping Object To Array

I would like to convert objects in JavaScript, but I'm not really sure of the best way to do it. I don't often code in the language so I don't really know much of the fundamentals- this is the object I get back from an API call in a React project:
{
"api": {
"results": 380,
"fixtures": [
{
"fixture_id": 65,
"league_id": 2,
"league": {
"name": "Premier League",
"country": "England",
"logo": "https://media.api-sports.io/football/leagues/2.png",
"flag": "https://media.api-sports.io/flags/gb.svg"
},
"event_date": "2018-08-10T19:00:00+00:00",
"event_timestamp": 1533927600,
"firstHalfStart": 1533927600,
"secondHalfStart": 1533931200,
"round": "Regular Season - 1",
"status": "Match Finished",
"statusShort": "FT",
"elapsed": 90,
"venue": "Old Trafford (Manchester)",
"referee": null,
"homeTeam": {
"team_id": 33,
"team_name": "Manchester United",
"logo": "https://media.api-sports.io/football/teams/33.png"
},
"awayTeam": {
"team_id": 46,
"team_name": "Leicester",
"logo": "https://media.api-sports.io/football/teams/46.png"
},
"goalsHomeTeam": 2,
"goalsAwayTeam": 1,
"score": {
"halftime": "1-0",
"fulltime": "2-1",
"extratime": null,
"penalty": null
}
}
]
}
}
I would like to convert it to this array (the array holds multiple objects):
[
{
"homeTeam": {
"id": 33,
"name": "Manchester United",
"teamId": 33
},
"awayTeam": {
"id": 46,
"name": "Leicester",
"teamId": 46
},
"outcome": {
"goalsScoredByAwayTeam": 2,
"goalsScoredByHomeTeam": 1
},
"resulted": true,
"type": "LEAGUE"
}
]
The teamId and id actually need to lookup another object before the final output.
I'm not sure what the best way to do it is. This is my function so far, trying to make use of optional chaining:
function convertFixturesToArray() {
fixturesStore.getFixtures()?.api?.fixtures?.length ? fixtures.api.fixtures.map(fixture => (
//TRANSFORMATION GOES IN HERE
)) : null;
}
You seem on the right track. It should be something like this (written in a slightly more modern JS)
convertFixturesToArray = () => fixturesStore.getFixtures()?.api?.fixtures?.map?.(fixture => {
//Do whatever check you need here with the fixture object
return {
homeTeam: { ...fixture.homeTeam },
awayTeam: { ...fixture.awayTeam },
outcome: {
goalsScoredByAwayTeam: fixture.goalsAwayTeam,
goalsScoredByHomeTeam: fixture.goalsHomeTeam,
},
type: 'LEAGUE',
resulted: true,
},
}) ?? [];
It looks like you're trying to get certain key/value pairs from your api response. With a mix of map, reduce, and find, you can get the values you're looking for by defining them in an array (i.e. desiredProps).
Of course, adding the "outcome" field and your other hardcoded fields would require a bit more logic on top of this. Boris' answer addresses this problem. I've taken a more flexible approach.
let apiResult = {
"fixtures": [
{
"prop1": "a1",
"prop2": "a2",
"prop3": "a3"
},
{
"prop1": "b1",
"prop2": "b2",
"prop3": "b3"
}
]
}
let desiredProps = ["prop2", "prop3"]
let result = apiResult.fixtures.map(x => {
return Object.keys(x).reduce((acc, curr) => {
if (desiredProps.find(y => y === curr)) {
acc[curr] = x[curr]
}
return acc
}, {})
})
console.log(result)

accessing a json child object not in an array

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);
});

cannot display JSON data from the backend in angular 2

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')
);

Categories