Home > Mobile >  How should I put 'key'?: Warning: Each child in a list should have a unique "key"
How should I put 'key'?: Warning: Each child in a list should have a unique "key"

Time:04-14

I encountered this error while writing this code. I thought since I am using map on array, this error occurred. so I tried to put 'key' there but couldn't find how to make it work. If I remove that line and try console.log(posts) then I can see my posts list on console.
Could anyone help me out here? Thanks in advance!

      export const list = async ctx => {
      // query는 문자열이기 때문에 숫자로 변환해 주어야 함
      // 값이 주어지지 않았다면 1을 기본으로 사용
      const page = parseInt(ctx.query.page || '1', 10);
      if (page < 1) {
        ctx.status = 400;
        return;
      }
    
      const { tag, username } = ctx.query;
      // tag, username 값이 유효하면 객체 안에 넣고, 그렇지 않으면 넣지 않음
      const query = {
        ...(username ? {'user.username': username} : {}),
        ...(tag ? { tags:tag } : {}),
      };
      try {
        const posts = await Post.find(query)
        .sort({_id: -1})
        .limit(10)
        .skip((page-1)*10)
        .exec();
        const postCount = await Post.countDocuments(query).exec();
        ctx.set('Last-Page', Math.ceil(postCount / 10));
        ctx.body = posts.map(post => ({
          ...post,
          body: removeHtmlAndShorten(post.body),
        }));
      } catch (e) {
        ctx.throw(500, e);
      }
    };

This is the error message

and below code is what it's rendering!

const PostItem = ({ post }) => {
  const { publishedDate, user, tags, title, body, _id } = post;
  return (
    <PostItemBlock>
      <h2>
        <Link to={`/@${user.username}/${_id}`}>{title}</Link>
      </h2>
      <SubInfo username={user.username} publishedDate={new Date(publishedDate)} />
      <Tags tags={tags} />
      <p>{body}</p>
    </PostItemBlock>
  )
}

const PostList = ({ posts, loading, error, showWriteButton }) => {
  // 에러 발생 시
  // if (error) {
  //   return <PostListBlock>Error occured</PostListBlock>
  // }
  return (
    <PostListBlock>
      <WritePostButtonWrapper>
        {showWriteButton && (
          <Button cyan to="/write">
          New post
        </Button>
        )}
      </WritePostButtonWrapper>
      {/* 로딩중이 아니고 포스트 배열이 존재할 때만 보여줌 */}
      {!loading && posts && (
        <div>
          {posts.map(post => (
            <PostItem post={post} key={post._id} />
          ))}
        </div>
      )}
    </PostListBlock>
  )
}

export default PostList;

CodePudding user response:

try this :

<div>
  {posts.map((post,index)=> (
    <PostItem post={post} key={index} />
  ))}
</div>

CodePudding user response:

so weirdly I solved this issue myself and I used this code below. I used round bracket on 'post' while using map and it successfully brought data. Hope it can help someone who has similar issue with me XD

const postCount = await Post.countDocuments(query).exec();
        ctx.set('Last-Page', Math.ceil(postCount / 10));
        ctx.body = posts.map((post) => ({
          ...post,
          body: removeHtmlAndShorten(post.body),
        }));
      } catch (e) {
        ctx.throw(500, e);
      }
    };
  • Related