trying to add user to database js - javascript

this code is used to add user to database
export const addUserInDB = (userEntityModel: UserEntityModel) => {
userEntityModel.id = '7';
return fetch(usersUrl, {
method: 'POST',
body: JSON.stringify(userEntityModel),
}).then((res) => res.json());
};
but it only returns this code in the database
{
"id": "Tcvpety"
}
And i want something like this
{
"id": "5",
"login": "luigi",
"password": "luigi125",
"email": "lluis.rubies#test.com",
"country": "Japan",
"type": "Customer",
"language": [
"Japanese",
"English"
]
},

Related

fetching from svelte store returns [object, object]

when I fetch this array and return it in the HTML I keep getting [object, object] or undefined. does anyone know if it's because of something I'm not defining in my svelte store?
For now, I'm just trying to get the name from the API.
here is the "league-store.js"
import { writable } from "svelte/store";
export const leagueStore = writable([]);
const fetchLeagues = async () => {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'API_KEY',
'X-RapidAPI-Host': 'v3.football.api-sports.io'
}
}
const url = `https://v3.football.api-sports.io/leagues?season=2022`;
const res = await fetch(url, options);
const data = await res.json();
const loadedLeagues = data.response.map((data) => {
return {
leagues: data
}
});
leagueStore.set(loadedLeagues);
}
fetchLeagues();
The +page.svelte
<script>
import { leagueStore } from "../../stores/league-stores";
console.log($leagueStore)
</script>
<div class="absolute top-[80px] right-0 w-[85vw] p-6">
{#each $leagueStore as leagues}
<p>{leagues}</p>
{/each}
</div>
and lastly the API im calling from as an example of the parameters
{
"get": "leagues",
"parameters": {
"season": "2022"
},
"errors": [],
"results": 815,
"paging": {
"current": 1,
"total": 1
},
"response": [
{
"league": {
"id": 351,
"name": "4. liga - Divizie B",
"type": "League",
"logo": "https://media.api-sports.io/football/leagues/351.png"
},
"country": {
"name": "Czech-Republic",
"code": "CZ",
"flag": "https://media.api-sports.io/flags/cz.svg"
},
"seasons": [
{
"year": 2022,
"start": "2022-08-05",
"end": "2023-06-10",
"current": true,
"coverage": {
"fixtures": {
"events": true,
"lineups": false,
"statistics_fixtures": false,
"statistics_players": false
},
"standings": true,
"players": false,
"top_scorers": false,
"top_assists": false,
"top_cards": false,
"injuries": false,
"predictions": true,
"odds": false
}
}
]
}
const loadedLeagues = data.response.map((data) => {
return {
leagues: data
}
});
Here data is an object of this form
{
"league": {
"id": 351,
"name": "4. liga - Divizie B",
"type": "League",
"logo": "https://media.api-sports.io/football/leagues/351.png"
},
"country": {
"name": "Czech-Republic",
"code": "CZ",
"flag": "https://media.api-sports.io/flags/cz.svg"
},
...
}
You could either map this to objects holding only the fields you need or use as is
const res = await fetch(url, options);
const data = await res.json();
leagueStore.set(data.response);
and access the fields like this
<div>
{#each $leagueStore as league}
<p>{league.league.name} - {league.country.name}</p>
{/each}
</div>
Since you tagged Sveltekit and are using an API key you might want to move the fetch logic to a page.server.js file or endpoint
https://kit.svelte.dev/docs/routing#page-page-server-js
https://kit.svelte.dev/docs/load
https://kit.svelte.dev/docs/load#making-fetch-requests
https://kit.svelte.dev/docs/routing#server

How to use selected value in React dropdown as api url id?

I want to render into table specific data from url with id taken after user select the needed value so here is my code:
fetching data for select options:
export default function Dashboard() {
const [value, setValue] = useState();
const [students, setstudents] = useState([]);
useEffect(() => {
const fetchStudents = async () => {
try {
const resp = await Axios({
method: "GET",
url: "https://jsonplaceholder.typicode.com/users",
headers: {
"Content-Type": "application/json",
},
});
setstudents(resp.data);
} catch (err) {}
};
fetchStudents();
}, []);
const classes = useStyles();
const [selected,setselected]=useState();
const options = students.map(s => ({
"value" : s.id,
"label" : s.username
}))
const handleChange = (event) => {
setselected(event.value);
};
now fetching data in dashboard function for selected value:
const [tabl, settabl] = useState([]);
useEffect(() => {
const fetchtabl = async () => {
try {
const resp = await Axios({
method: "GET",
url: "https://jsonplaceholder.typicode.com/users"+{selected},
headers: {
"Content-Type": "application/json",
},
});
settabl(resp.data.surveys);
} catch (err) {
console.log(err);
}
};
fetchtabl();
}, []);
const getTableData = (tabl) => {
return tabl.map((tab) => [
tab.id,
tab.name,
tab.username,
]);
};
now render data in return:
Select the course:
<Select options={options} onChange={handleChange}/>
<Table
tableHead={["Course Code", "Course Name", "Survey Link"]}
tableData={getTableData(tabl)}
tableHeaderColor="primary"
/>
but nothing appear after select the value needed how can i fix it and does react allow to use selected value like this?
data
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan#yesenia.net",
"address": {
"street": "Douglas Extension",
"suite": "Suite 847",
"city": "McKenziehaven",
"zipcode": "59590-4157",
"geo": {
"lat": "-68.6102",
"lng": "-47.0653"
}
},
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
},
So based on the conversation in the comment section the value is there in selected. Then the only problem is useEffect is not triggered on change because of empty dependency array.
I suggest few modifications in your code:
Add to the dependency array selected as [selected] which will trigger the function once you have change on that state.
Check for null or undefined values in order not to concatenate without value.
Also I added one extra slash into your URL after users so now it's users/.
So the URL would be at the end of the day:
`https://jsonplaceholder.typicode.com/users/${selected}`
Based on the explanation try as:
useEffect(() => {
const fetchtabl = async () => {
try {
const resp = await Axios({
method: "GET",
url: `https://jsonplaceholder.typicode.com/users/${selected}`,
headers: {
"Content-Type": "application/json",
},
});
settabl(resp.data.surveys);
} catch (err) {
console.log(err);
}
};
if (selected) {
fetchtabl();
}
}, [selected]);
+1 suggestion:
Maybe it's not related but you have in .map() an extra [] which might be not needed, so try as:
const getTableData = (tabl) => {
return tabl.map((tab) => ({
tab.id,
tab.name,
tab.username,
}));
};
In this way .map() will return an array of objects with the properties of id, name, username.

How to access a JSON key with .filter()

How would I filter out the following Titles using .filter? I'm expecting the output to be something like: {"Capuchin Monkey", "Capybara"} I'm working with JSON that looks like this:
{
"d": {
"results": [
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Courses": {
"results": [
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Title": "Capuchin Monkey"
},
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Title": "Capybara"
},
JS snippet:
// Courses/Title is what I'm interested in
axios.get([redacted] + "/getByTitle('Categories')/items?$select=Title,Description,Courses/Title,SortOrder&$expand=Courses&$orderby=Title&$top=1000",
{
method: "GET",
credentials: "include",
mode: "no-cors",
headers: {
"Accept": "application/json; odata=verbose"
}
}),
// irrelevant code
]).then(axios.spread((cat, lib, admn) => {
_categories = cat.data.d.results; // -------- //
this.loadCategories();
})).catch(error => {
console.log(error);
});
getCategories(){
return _categories;
}
loadCategories(){
let categs = _categories,
trainingCrs = _categories.d.results.filter(x => {
return {
"crsTitle": x.Courses.results.Title // code smell
}
});
I think you need is map, not filter.
Something like this:
var json = { "results": [
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Courses": {
"results": [
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Title": "Capuchin Monkey"
},
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Title": "Capybara"
}]}}]};
const reducedResult = json.results.reduce((act, val)=> act.concat(val));
const titles = reducedResult.Courses.results.map((value)=>value.Title);
console.log(titles);
To get a list of Titles such as {"Capuchin Monkey", "Capybara"}, you better use Array​.prototype​.map()
rather than Array​.prototype​.filter()
.
var json = {
"d": {
"results": [
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Courses": {
"results": [
{
"__metadata": {
"id": "N/A",
"type" : "N/A"
},
"Title": "Capuchin Monkey"
},
{
"__metadata": {
"id": "N/A",
"type": "N/A"
},
"Title": "Capybara"
}
]
}
}
]
}
}
// Use of .map
trainingCrs = json.d.results[0].Courses.results.map(x => x.Title);
console.log("Training title list: ", trainingCrs);
// Use of .filter
trainingCrs = json.d.results[0].Courses.results.filter(x => x.Title === "Capybara");
console.log("Training list filter on one Title", trainingCrs);
loadCategories(){
let categs = _categories,
trainingCrs = _categories.d.results.map((x) =>x.Courses.results.Title)
});

Not getting the expected response from Backend in web service

I wrote an api call in AngularJS to get data from backend JAVA
Here is my code
$scope.memberForm = {};
$scope.memberForm.member_address = {};
$scope.memberRegForm = function() {
$scope.btnloading = true;
$('#add-btn').prop('disabled', true);
url = '/member/add';
var request = $http({
method: "post",
url: url,
data: angular.toJson($scope.memberForm),
headers: {
'Content-Type': 'application/json'
},
});
}
But I am not getting desire response from backed, Response that's I am actually getting from backend is
{
"fullname":"sdfgsdf",
"fathername":"sdfsdf",
"email":"sdfsdf#gmail.com",
"date_of_birth":"1993-03-24",
"admission_date":"2018-10-22",
"phoneno":"0987654321",
"nationality":"United States",
"member_address":
{
"address":"5 meadow st",
"state":"Connecticut",
"zipcode":"06770",
"district":"zc"
},
"college":"cvbcv",
"qualification":"bcvbcv",
"slno_ivpr":"12"
}
But here is my desire response. I need member_address as an array of ojects instead of a single object
{
"fullname": "avinash",
"fathername": "xxxxxxx",
"date_of_birth": "1991-08-08",
"nationality": "indian",
"admission_date": "2015-08-08",
"college": "ABC college",
"slno_ivpr": null,
"phoneno": "1234567890",
"email": "avinash.mitresource#gmail.com",
"remarks": "no remarks",
"member_renewal": [],
"qualification": "MCA",
"member_address": [
{
"address": "piratlanka,repalle",
"state": "AP",
"district": "Guntur",
"zipcode": "522264",
"type": "PermanentAddress"
},
{
"address": "padamata",
"state": "AP",
"district": "vijayawada",
"zipcode": "522201",
"type": "ResidencialAddress"
}
]
}

How can i check if the child object has the id inside it?

I have seller and buyer information inside an array, i need to check if the id matches with either seller or buyer id inside the array, then i need to remove the object from the array.
here is the array:
[
{
"transactionId": null,
"buyer": {
"userId": "eu-central-1",
"email": "pic#gmail.com",
"firstName": "pic",
"lastName": "1",
"_id": "5902ca3ce201550655a7bbf8"
},
"seller": {
"userId": "eu-central-2",
"email": "pic2#gmail.com",
"firstName": "pic",
"lastName": "2",
"_id": "5902ca3ce201550655a7bbf7"
}
}
]
i have the userid eu-central-2. i want the expected output as,
[
{
"transactionId": null,
"user": {
"userId": "eu-central-1",
"email": "pic#gmail.com",
"firstName": "pic",
"lastName": "1",
"_id": "5902ca3ce201550655a7bbf8"
}
}
]
what i tried
let data = results.filter(result=> seller.userId || buyer.userId == userId);
the problem is the removal part and renaming the User.
var userId = 'eu-central-2';
var results = [
{
"transactionId": null,
"buyer": {
"userId": "eu-central-1",
"email": "pic#gmail.com",
"firstName": "pic",
"lastName": "1",
"_id": "5902ca3ce201550655a7bbf8"
},
"seller": {
"userId": "eu-central-2",
"email": "pic2#gmail.com",
"firstName": "pic",
"lastName": "2",
"_id": "5902ca3ce201550655a7bbf7"
}
}
];
If you want to remove the entire object, use this one:
var data = results.filter(function(a) {
if(a.buyer.userId == userId || a.seller.userId == userId) {
return false;
}
return true;
});
Or if you want to remove the specific buyer or seller, use this:
var data = results.filter(function(a) {
if(a.buyer.userId == userId) {
delete a.buyer;
} else if(a.seller.userId == userId) {
delete a.seller;
}
if(a.buyer) {
a['user'] = a.buyer;
delete a.buyer;
} else if(a.seller) {
a['user'] = a.seller;
delete a.seller;
}
return true;
});
console.log(data);
I would suggest the following code:
results.map(result => ({
transactionId: result.transactionId,
user: [result.buyer, result.seller]
[1-[result.buyer, result.seller].findIndex(user => user.userId === userId)]
})).filter(result => result.user);
const results = [
{
"transactionId": null,
"buyer": {
"userId": "eu-central-1",
"email": "pic#gmail.com",
"firstName": "pic",
"lastName": "1",
"_id": "5902ca3ce201550655a7bbf8"
},
"seller": {
"userId": "eu-central-2",
"email": "pic2#gmail.com",
"firstName": "pic",
"lastName": "2",
"_id": "5902ca3ce201550655a7bbf7"
}
}, {
"transactionId": null,
"buyer": {
"userId": "eu-central-3",
"email": "pic#gmail.com",
"firstName": "pic",
"lastName": "1",
"_id": "5902ca3ce201550655a7bbf8"
},
"seller": {
"userId": "eu-central-4",
"email": "pic2#gmail.com",
"firstName": "pic",
"lastName": "2",
"_id": "5902ca3ce201550655a7bbf7"
}
}
];
const userId = "eu-central-2";
const data = results.map(result => ({
transactionId: result.transactionId,
user: [result.buyer, result.seller]
[1-[result.buyer, result.seller].findIndex(user => user.userId === userId)]
})).filter(result => result.user);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You need to be a bit more specific with your statement because javascript might not do what you expect. If I understand it correctly you want the following:
seller.userId === userId
OR
buyer.userId === userId
If that is what you want the used statement wouldnt work because JS will see it as:
seller.userId === true
OR
buyer.userId === userId
What you probebly need to do is just mention userId twice and use parenthesis like this: (seller.userId == userId) || (buyer.userId == userId)

Categories