TIL

230809) Array.prototype.map() expects a value to be returned at the end of arrow function 문제 해결

유이 YUI 2023. 8. 9. 20:56
{data?.map((post) => {
          if (post?.uid === user?.uid) {
            return (
              <ListBoxContainer key={post.id}>
                <ListBox
                  key={post.id}
                  onClick={() => {
                    showPostHandler(post);
                  }}
                >
                  <p>{post?.userConcern}</p>
                </ListBox>
                <Button
                  variant="contained"
                  sx={{
                    backgroundColor: '#868686',
                    transition: '0.3s',
                    ':hover': { backgroundColor: '#666' }
                  }}
                  onClick={() => {
                    deletePostHandler(post.id);
                  }}
                >
                  <DeleteIcon sx={{ fontSize: '18px', marginRight: '5px' }} />
                  <span>삭제</span>
                </Button>
              </ListBoxContainer>
            );
          }
        })}

해당 코드에서 지속적으로 Array.prototype.map() expects a value to be returned 
at the end of arrow function라는 경고문이 발생하였다. '경고'이기에 잘 돌아가긴 하지만 Warning 없이 깔끔한 방법이 좋기 때문에 해결방법을 찾아냈다. 결론적으로 해당 문제는 아주 간단하게 해결 가능하다

{data?.map((post) => {
          if (post?.uid === user?.uid) {
            return (
              <ListBoxContainer key={post.id}>
                <ListBox
                  key={post.id}
                  onClick={() => {
                    showPostHandler(post);
                  }}
                >
                  <p>{post?.userConcern}</p>
                </ListBox>
                <Button
                  variant="contained"
                  sx={{
                    backgroundColor: '#868686',
                    transition: '0.3s',
                    ':hover': { backgroundColor: '#666' }
                  }}
                  onClick={() => {
                    deletePostHandler(post.id);
                  }}
                >
                  <DeleteIcon sx={{ fontSize: '18px', marginRight: '5px' }} />
                  <span>삭제</span>
                </Button>
              </ListBoxContainer>
            );
          } else {
            return null;
          }
        })}

위 코드처럼 if문의 마지막 부분에 아래의 else 구문을 넣어 주면 간단히 해결된다! return 을 어디다 넣어야 되는지 삼항연산자를 써야 되나? 허둥지둥 정신 없었는데 매우 간단히 해결되는 문제였다!

 else {
            return null;
          }

 


복습을 위한 강의 판서

 

브이하는 사진

오늘도 잘 해냈다!