Home > front end >  why do we use curly braces while defining constant variable in react js?
why do we use curly braces while defining constant variable in react js?

Time:04-07

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?

CodePudding user response:

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);
  • Related