0

I am learning react and get stuck in the following line of code:

const { favourites } = this.state

Can someone please help me?

Sachin
  • 1,206
  • 12
  • 13
  • 1
    It's equivalent to `const favourites = this.state.favourites`. Read about Destructuring assignment https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring – Sid Vishnoi Aug 11 '19 at 18:29
  • Possible duplicate of [What does { ...obj1, obj2 } do exactly](https://stackoverflow.com/questions/55685270/what-does-obj1-obj2-do-exactly) – wentjun Aug 11 '19 at 19:40

3 Answers3

2

that isn't React-specific, it is a JavaScript (ES6) feature called destructuring:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

James South
  • 534
  • 4
  • 15
0

What this means is that the const favorites is equal to the value of favorites in the state of the component. So if the value of favorites is 22 in the state, the const favorite is equal to 22.

const { favourites } = this.state

is same as

const favourites = this.state.favourites

Somename
  • 3,376
  • 16
  • 42
  • 84
0

Also, an important note is that by using const, you're making the state.favorites prop read-only. Also, you can use it for any object. Let's say I had an employee object with employeeId, lastName, firstName props, etc. Let's say I get an array of employee objects, I can use this construct to greatly simplify the code.

render() {  
  const {UserName, EmailAddress, AccountCreated, PasswordChanged, AccountName,
    Locked, Enabled} = this.props.ewdsUser; 

return (       
    <tr>
        <td>{UserName}</td>
        <td>{EmailAddress}</td>
        <td>{AccountCreated}</td>
        <td>{PasswordChanged}</td>          
        <td>{Locked}</td>       
        <td>{Enabled}</td>  

This prevents me from having to do this:

render() {  

return (       
    <tr>
        <td>{this.props.UserName}</td>
        <td>{this.props.EmailAddress}</td>
        <td>{this.props.AccountCreated}</td>
        <td>{this.props.PasswordChanged}</td>           
        <td>{this.props.Locked}</td>        
        <td>{this.props.Enabled}</td>   
Charles Owen
  • 2,403
  • 1
  • 14
  • 25