How to send data to an api having multiple Nested Arrays in react - reactjs

I have to send the modified data to an api which has json format as below:
{
"Customer": {
"name": "ABC",
"email": ABC#gmail.com,
"password": ""
},
"access": true,
"time": 2000
}
On save I want to set the respective state to api fields.
save=()=>{
let newCustomer={
access:this.state.access,
time:this.state.time,
name: //How can i set the state values for name,email and
password which is in nested form?
email:
password:
}
return axios.put('api',newCustomer)
.then(response => {
})
}

You can directly declare it like your json format.
let newCustomer={
access:this.state.access,
time:this.state.time,
Customer: {
name: ..., // state name from your nested form
email: ..., // state email from your nested form
password: ..., // state password from your nested form
},
}

save=(Customer)=>{
let newCustomer={
...Customer,
access: this.state.access,
time: this.state.time,
}
return axios.put('api', newCustomer)
.then(response => {
console.log(response);
})
}
Then newCustomer will be like Customer but access and time may be different.
In backend you cann access customer name and email like you are accessing an array

Related

How to use if condition inside an object in react

I'm trying to pass some data as payload to the api and I'm struggling to put condition inside of the object. I have an object called payload and I want to pass it in the api by checking the value of the state called profession.
const payload ={
name: registerData.fullname,
password: registerData.password,
confirm_password: registerData.confirmPassword,
email: registerData.email,
additional_info: {
profession == "Student" ? (
universityname: values.universityname,
course: values.course,
start_year: values.start_year,
end_year: values.end_year, ) :
(professorUniversity: values.professorUniversity,
department: values.department,
organizationName: values.organizationName,
organizationLocation: values.organizationLocation,
investorCompany: values.investorCompany,
investorCompanyWebsite: values.investorCompanyWebsite,
companyName: values.companyName,
govtSector: values.govtSector,
govtDesignation: values.govtDesignation,
)
},
};
// I'm passing the payload in the api.
api.post("some-url/register", payload);
as you can see in the top I want to pass the entire key and value if the condition is true. If the profession is not student I don't even pass the universityname key.
You should use a combination of ternary and spread operator
const payload ={
name: registerData.fullname,
password: registerData.password,
confirm_password: registerData.confirmPassword,
email: registerData.email,
additional_info: {
...(profession == "Student" ? {
universityname: values.universityname,
course: values.course,
start_year: values.start_year,
end_year: values.end_year, } :
{professorUniversity: values.professorUniversity,
department: values.department,
organizationName: values.organizationName,
organizationLocation: values.organizationLocation,
investorCompany: values.investorCompany,
investorCompanyWebsite: values.investorCompanyWebsite,
companyName: values.companyName,
govtSector: values.govtSector,
govtDesignation: values.govtDesignation,
})
},
};
I have explained something similar here
An example:
let car = "BMW";
const result = {
...(car === "BMW" ? {
make: "Germany"
} : {
make: "other"
})
};
console.log(result);

How to perform Patch

I have a login form, which I have implemented using reactive forms. I have created a static table also, once the login form is filled and clicked the save button, all the values will be populated in to that table. I need to implement an edit button in that table. Once the edit button got clicked all the table values should be populated back to the login form. How should I implement this in Angular 13
1. Find the userId that you need to update (create an edid button on each table item which gives you the id).
2. If its an array your can use find Index
3. Now update your array index to the given value.
// Login Table List
let loginList = [
{ userID: 1, userName: 'Alex' },
{ userID: 2, userName: 'Bob' },
{ userID: 3, userName: 'Soni' }
]
// Update function
const update = (userID, userName) => {
let index = loginList.findIndex((userName, index) => userName.userID === userID);
loginList[index] = { userID: userID, userName: userName }
}
update(1, 'George');
console.log(loginList);
/*
// Updated Login List
[
{ userID: 1, userName: 'Geroge' },
{ userID: 2, userName: 'Bob' },
{ userID: 3, userName: 'Soni' }
]
*/

sending multiple objects using axios

How can I send multiple objects in axios ? is there a way to send an array to an API using axios ?
This is the code.
export const addOrderAdmin = (ownerID,array) => api.patch(`/checkout/${ownerID}`,
{
delivery: array // array with 2 objects.
}
)
and the objects was like this.
is it possible ?
you could always create an array of nested objects
example:
var customerInfo = {
name: 'bob',
phone : 'xxx-xxx-xxxx',
address: [
{
id: 1,
city: 'Buffalo'
},
{
id 2,
city: 'Houston'
]
}
then you could just patch the customerInfo object and you can use interpolation with dot accessor notation for the url

Insert list data over the iteration(map)

Here I am trying to modify my data over the iteration and send some result to API call.
The API Call receives a request with a structured data format which is
{ list: [{ id: "1", name: "Hello" }, ... ] }
Somehow I managed to call the API with single data ( const params in my current code, it only accepts single data).
But now it has to be done with multiple data something like this:
{ list: [{ id: "1", name: "Hello" }, { id: "22", name: "Ed" }, { id: "36", name: "Jason" } ... ] }
Here is my current code
const [table, setTalbe] = useState(..); // assume, we have some table data here
const processNow = () => {
let id = 0;
let name = '';
// if table length is greater than 1, we go for the loop.
if (table.length >= 1) {
table.map(data => {
id = data.userId;
name = data.userName;
});
//insert table data to params, here I want to add whole table data into "list"
//the final result of this list should be something like this
//ex ) list: [{ id: '123', name: 'Josh' }, { id: '125', name: 'Sue' }, { id: '2222', name: 'Paker' } ...],
// but how??
const params: any = {
list: [
{
id: id,
name: name
},
],
};
//send PUT reqeust with params
axios
.put(
'/api/v1/tosent',
params,
)
.then(res => {
console.log('The response', res);
})
.catch(err => {
console.log('The error: ', err);
});
}
};
but I'm stuck with it, please help me to finish this code to work properly.
need your kind advice.
Array.prototype.map returns a new array with the function you pass applied to every element. You should study the MDN documentation on map to understand its use.
Your current code does nothing with the map return value:
table.map(data => {
id = data.userId;
name = data.userName;
});
You probably assumed .map would mutate the data, as in change it in place. Instead, the whole operation returns a new array.
It looks like you want to do:
const list = table.map(data => {
return {
id: data.userId,
name: data.userName
}
});
This is applying a function to every element in the array that will map each element to a new object, matching your question, with an id and name key. Then it looks like you want to pass the returned value of map (which we named list above) to your call:
const params: any = {
list: list
};

DynamoDb: UpdateExpression for updating arrays

Env: NodeJS service using aws-sdk for interacting with DynamoDb.
Problem: When I set an attribute of an item to an array, it is saved as a string. I expect x: ['1'] but I get x: '1'. I believe this is because I'm incorrectly writing my UpdateExpression/ExpressionAttributeValues.
Situation: I have a table with a field called users. Users is an array of uuids that can be updated. An example of an item in the table:
{ x_name: 'Hello',
owner: '123456',
x_uuid: '1357911',
users: []
}
I want to update the users array with a user uuid. To my update function I pass through:
{ users: ['13245395'] }
The update function (data is { users: ['13245395'] }):
updateX(data, { x_uuid }) {
if (!x_uuid) {
throw new Error('No x_uuid supplied')
}
// new doc client
const docClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: this.table,
Key: {
'x_uuid': x_uuid
},
UpdateExpression: "set users = :users",
ExpressionAttributeValues:{
":users": `${data.users}`
},
ReturnValues:"ALL_NEW"
};
return new Promise((resolve, reject) =>
docClient.update(params, (error, x) => {
return error ? reject(error) : resolve(x)
})
)
}
}
The result I get is
{ x_name: 'Hello',
owner: '123456',
x_uuid: '1357911',
users: '13245395'
}
but what I expected was:
{ x_name: 'Hello',
owner: '123456',
x_uuid: '1357911',
users: ['13245395']
}
Previously tried:
wrapping data.users in an array when creating params (works for the first id but the second id added gets appended to the same string as the first so it looks like ['123,456'] instead ['123', '456'].
UpdateExpression: "set users = :users",
ExpressionAttributeValues:{
":users": [${data.users}]
},
Using the "L" and "S" data types to determine that it's an array of strings, i.e.
UpdateExpression: "set users = :users",
ExpressionAttributeValues:{
":users": { "L": { "S":${data.users} } }
},
You are converting your users array to a string
":users": `${data.users}`
Try
":users": data.users
This will set users to the array in data.users

Resources