'why do we use curly braces while defining constant variable in react js?

i write this following code to fetch the title from props . Before:

export default function Articleinfo(props) {
    const  {edge}  = props.data.allNodeArticle;
    
    return(
        <>
          <div>
              <h1>Title:{edge[0].title}</h1>
              <h2>info:</h2>
          </div>
        </>
    );
};

i getting this error : Cannot read properties of undefined (reading '0')

But After : When i remove the curly braces it worked

export default function Articleinfo(props) {
    const  edge  = props.data.allNodeArticle;
    console.log(edge.nodes[0].title);
    const Title = edge.nodes[0].title;
    return(
        <>
          <div>
              <h1>Title:{edge.nodes[0].title}</h1>
              <h2>info:</h2>
          </div>
        </>
    );
};

Can some explain me why this happen? what is the concept behind it?



Solution 1:[1]

Curly braces are used for Object destructuring

In the link below syntax for object destructing is explained

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

So when you do

    const  {edge}  = props.data.allNodeArticle;

this means that the object allNodeArticle has a key named edge and you are accessing it

But when you do the followinng and error goes it means allNodeArticle is not an object having a key edge instead it has array nodes it.

const  edge  = props.data.allNodeArticle;
console.log(edge.nodes[0].title);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 coffee