the use of ... element in jsx file [duplicate] - javascript

This question already has answers here:
javascript es6 array feature [...data, 0] "spread operator"
(2 answers)
Closed 5 months ago.
I am a beginner at React learning it from an online tutorial.
there is an element used in one of the courses which is ... and can be seen in the following code
handleIncrement = (productId)=>{
const newProducts=[...this.state.products]
const index= newProducts.findIndex(p=> p.id === productId)
newProducts[index].count +=1 ;
this.setState({products : newProducts});
}
its usage seems to be creating an array from products and passing it to the newProducts which is an array now. could you please explain what exactly do ... and when we need it to use?

It's called the spread syntax.
In react, you're not supposed to mutate the state directly. So, if you have an array you want to edit, you will first create a copy of the array with the spread syntax, edit the new array, and finally set the state to the edited copy of the array.
Creating a copy with newProducts = this.state.products is not sufficient in this case as both the variables are pointing to the same object in memory and changing newProducts is the same as changing `this.state.products.

Related

Update one object of an array using spread operator not working [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 8 months ago.
I want to update one object from an array. This is my current working code which is updating the object inside the array
var equipment = this.equipments.find((e) => e.id === this.currentItem.id);
// this property is getting updated successfully in the array
equipment.countryId = this.currentItem.countryId;
But I have many properties in that object so I tried to use spread operator to fully copy the object to the existing object like this
var equipment = this.equipments.find((e) => e.id === this.currentItem.id);
equipment = { ...equipment, ...this.currentItem };
But this does not work. It does not update the object in the array.
Could be because the spread operator totally creates a new object and does not update the existing object?
Is there a way if not spread operator to update all the properties of the object with the new values without needing to explicitly write it for all properties?
Could be because the spread operator totally creates a new object and does not update the existing object?
Yes, you need to return a new array and replace one element, it can be done using array.map:
this.equipments = this.equipments.map(equipment => {
if(equipment.id === this.currentItem.id){
return { ...equipment, ...this.currentItem };
}
return equipment;
});

Spread operator working in console.log and not working when trying to return or set in variable [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 1 year ago.
So, I have a problem with a spread operator which is really annoying me right now. I searched a lot and nothing helped me.
When I used console.log(...val) it shows data perfectly without any error, but when I try const data = ...val it throws an error 'Expression expected'
{stats &&
stats.map(val => {
const title = Object.keys(val)[0]
const values = Object.values(val)
console.log('*************', ...values)
return (
<div className="stats__stats--chart">
<div className="chart-name">
<h3>{title}</h3>
</div>
<div className="chart-data">
<DataChart data={values} />
</div>
</div>
)
})}
I am using React and Typescript and I know this should work since I've done it before.
const values is a 2D array, inner arrays hold objects and I want to extract all arrays from that array so I can use it with that chart, but spread operator is broken somehow. Is there some kind of config to fix that? Whats the problem with that
I am not sure how you use the values, but if you use the data in the DataChart component you should use [...data[0], ...data[1]] as variable.

Updating Const variable thorough another file [duplicate]

This question already has answers here:
const or let in React component
(4 answers)
Closed 2 years ago.
I am very new to React and i don't know how to achieve the following case :
I have Variable declared in Config file
Say
Const a= "Some value"
and i want to update that value from different file when certain conditions are met
Assume :
if (true){a= "New Value"}
const is an immutable variable. If you want to have a mutable (changable) variable, use let instead.
You can only initialize a "Const" once!
That's the main difference to all the other ways you can create a variable.

Convert underscore in ES6 Methods [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 4 years ago.
I have an existing codebase that uses AngularJS, Redux and Underscore. In that codebase I have the following code:
const selectedBroker = _.findWhere(state.brokers, { brokerId: action.payload });
return state.merge({
selectedBroker,
selectedBrokerId: action.payload,
});
I want to convert it to an es6 Method. I think the find(), would be suitable, but don't know how. Could you help me a little bit? Thanks!!
Also it is not in the scope of this task but I see more underscore methods here. Like _.reject, _.contains, _.map. Could you also convert that in the context similar to the above code example.
It will be just like below, array.find will return the first matching element in the array.
let selectedBroker = state.brokers.find(broker => broker.brokerId == action.payload);

Better mapping JSON to objects in JavaScript [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Access Javascript nested objects safely
(14 answers)
Test for existence of nested JavaScript object key
(64 answers)
Closed 5 years ago.
I'm using v4 sheets API from google-api-nodejs-client, it returns a lot of data. Though I filter it using fields arguments, the structure of JSON is very complex. So to incorporate it into my logic, I flatten it. And it needs to be safe, I don't want any exceptions to be thrown.
This is how the UNSAFE version of the code looks:
const data = response.sheets[0].data;
const columns = data.map((column) => {
const rowData = column.rowData;
const values = rowData[0].values;
return rowData.map((cellData) => cellData.values[0].userEnteredValue);
});
// ...
If JSON is invalid, an exception is inevitable. I don't want this. The problem is that to fix it, I should add plenty of if-s. This would make the code look ugly.
Let's summarize: Is there a way to map JSON into local objects safely and expressive (and preferably relying only on features of ES6)?
UPDATE
Let's add a little more context. This is a small insight how deep the JSON is, and all I need to map it to an array of strings ('1.06' is one of them).
{
"sheets":[
{
"data":[
{
"rowData":[
{
"values":[
{
"userEnteredValue":{
"stringValue":"1.06"
}
}
]
},
...

Categories