Caballo de Utec

Podemos encontrar esta obra en el piso 10 de la universidad UTEC, suspendida en lo alto del directorio. El tipo de exhibición no tiene una finalidad de ser presentada para un público en general, al…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




The Spread Operator

I’m going to butter your bread…

I recently came across some handy patterns using the spread operator so I thought I’d write up a quick blog post sharing some.

Javascript has this lovely thing it does with objects. Whenever you attempt to make a copy of an object you might inadvertently make a reference to it instead.

Mutating data can lead to some hard to find bugs, so it’s worth the time and effort to ensure that you prevent this by properly copying any data that you need to change. One way is through the use of the spread operator.

Any changes to newNed will not mutate the oldNed variable. However, there is one exception. The spread operator does not preform a deep clone of a nested object.

To get around this you have to also spread out the nested array

Keep in mind that if you have a deeply nested object you might want to reach for some kind of custom function or library to help you with deep cloning.

Here’s some other nifty immutable tricks.

2. Copying an object and simultaneously updating properties

How about converting a nodeList into an actual array?

So, I haven’t personally found many use cases for the Rest Operator yet. However, I did stumble across this pattern for creating authenticated routes in React using React-Router. Here’s a basic example.

The rest operator magic happens when you return <Route {...rest} /> . Basically, what’s going on is a function AuthenticatedRoute is called and it checks for an id on the state object. If it fails, it returns a <Redirect/> component. Otherwise, it returns a <Route> component and passes through all its props (in this example a path , data , and render).

Pretty handy right? Got anymore? Share them below please!

Add a comment

Related posts:

Teslacoin added to 2 more exchanges

We are pleased to announce that -$TES is now included in 2 more exchanges:. “Teslacoin added to 2 more exchanges” is published by Tesla Starter.