Search code examples
javascriptreactjsreact-props

React : props are undefined but when i console.log(props), it works


I have an arrow function that returns this:

  return (
    <div className="posts">
      <Post />
      {dataApi.map((post) => {
        return <Post post={post} key={uuidv4()} />;
      })}
    </div>
  );
};

In my Post component, I try to import the author, the date and the text passed in props, but it tells me that this data is undefined. However, when I console.log (post), my data appears ... here is the code :

const Post = ({post}) => {
  //const {author, date_creation, message} = post
  return (
    <div className="post">
      <div className="post__author_group">
        <Avatar className={"post__avatar"} />
        <div className="post__author_and_date">
          <Author className="post__author" author={'author'} />
          <Date className="post__date" date={'date_creation'} />
        </div>
      </div>
      <Text message={'message'} />
      {/* <Media /> */}
      <Interactions />
    </div>
  );
};

If i console.log(post), i can see my 5 objects, but if I uncomment "//const {author, date_creation, message} = post" and replace author = {'author "} with author = {author} (which is a prop), it puts me" TypeError: Cannot destructure property' author 'of' post 'as it is undefined ."

I don't know if it's related but when I console.log (post), in my console before I have my objects, I have two "undefined" but I don't know where it came from. My console :

Post.js: 12 undefined
Post.js: 12 undefined
Post.js: 12 {id: 1, message: 'Hello World', date_creation: '2020-11-11T10: 11: 11.000Z', author: 'Vincent'}
Post.js: 12 {id: 2, message: 'Hello World', date_creation: '2020-11-11T10: 11: 11.000Z', author: 'Vincent'}
Post.js: 12 {id: 3, message: 'Hello World', date_creation: '2017-06-29T15: 54: 04.000Z', author: 'Vincent'}
Post.js: 12 {id: 4, message: 'Hello World', date_creation: '2021-09-03T13: 50: 33.000Z', author: 'Vincent'}
Post.js: 12 {id: 5, message: 'Hello World', date_creation: '2021-09-03T13: 50: 49.000Z', author: 'Vincent'}

Solution

  • It is because your data is not loaded when your component is first time loaded. Try this:

    const Post = ({post}) => {
    if(post){
     const {author, date_creation, message} = post // You can destructure here 
     return (
        // ....
      );
    }
    else return null;
    };
    

    OR

    Load the above component if you received all your data

     return (
        <div className="posts">
          <Post />
          {dataApi && dataApi.length > 0 && dataApi.map((post) => {
            return <Post post={post} key={uuidv4()} />;
          })}
        </div>
      );