개발자 되는 중/TIL&WIL

내배캠 TIL 2022.12.26

SeonChoco 2022. 12. 26. 16:37

프로젝트 기능 구현하는 과정

 

삭제, 수정 토글 버튼 만들기

 

리액트에서 어떤 식을 하는 것이 좋을까 하면서 검색하다가 활용하기 좋은 삼항연산자를 이용한 코드를 찾았다. 

https://stackoverflow.com/questions/64572972/using-refs-to-style-a-div-element

 

Using Refs To Style A Div Element

Good day, I'm new to react JS and I want to get a div element using refs and style it. It gives an error(can't read the property style of undefined). import React, { useState, useRef } from 'react'

stackoverflow.com

 

삭제 state랑 수정 state를 두 개다 조건으로 주어서 하나만 false로 바뀌어도 둘 다 상태가 변경될 수 있도록 하는 것이 되나? 하고 코드를 넣었는데 원하는 대로 실행이 되어서 굉장히 기뻤다.

 <div style={{ display: showDelete && showEdit ? "block" : "none" }}>

 

전체 코드 

 // show 여부를 결정하는 state
  const [showEdit, setShowEdit] = useState(true);
  const [showDelete, setShowDelete] = useState(true);

  //수정 input 토글
  const toggleEditInput = () => {
    setShowEdit((current) => !current);
    setPassword("");
  };

  // 삭제 input 토글
  const toggledeleteInput = () => {
    setShowDelete((current) => !current);
    setPassword("");
  };

  return (
    <div>
      <p>닉네임: {user}</p>

      <p style={{ display: showEdit ? "block" : "none" }}>내용: {content}</p>
      <input
        style={{ display: showEdit ? "none" : "block" }}
        value={commentContent}
        onChange={(e) => setCommentContent(e.target.value)}
      />
      <p>임시 비번: {pw}</p>
      <p>{time}</p>

      <div style={{ display: showDelete && showEdit ? "block" : "none" }}>
        <button onClick={toggledeleteInput}>삭제</button>
        <button onClick={toggleEditInput}>수정</button>
      </div>

      <div style={{ display: showEdit ? "none" : "block" }}>
        <input
          type="password"
          onChange={(e) => setPassword(e.target.value)}
          placeholder="비밀번호"
          value={password}
        />
        <button
          onClick={() => {
            OnClickEditCommentHandler(id);
          }}
        >
          수정완료
        </button>
        <button onClick={toggleEditInput}>취소</button>
      </div>

      <div style={{ display: showDelete ? "none" : "block" }}>
        <input
          type="password"
          onChange={(e) => setPassword(e.target.value)}
          placeholder="비밀번호"
          value={password}
        />
        <button onClick={() => onClickDeleteHandler(id)}>삭제완료</button>
        <button onClick={toggledeleteInput}>취소</button>
      </div>
    </div>
  );
};

 

댓글 최신순으로 불러오기

 

json 서버 조건문

https://sewonzzang.tistory.com/4

 

json-server (2) : 조건문 사용하기

https://sewonzzang.tistory.com/3 json-server 사용하기 json-server는 아주 짧은 시간에 REST API를 구축해주는 라이브러리입니다. 하지만, REST API 서버의 기본적인 기능을 대부분 갖추고 있습니다만, 프로덕션

sewonzzang.tistory.com

최신순으로 댓글을 불러오게 하고 싶어서, 시간순서대로 정렬하고 내림차순으로 불러왔다.

 

sort() 오름차순

reverse() 뒤집기

https://redcow77.tistory.com/509

 

[Javascript] 자바스크립트(JS)의 객체정렬함수 - sort(), reverse()

자바스크립트(Javascript)의 객체 정렬하기 자바스크립트(Javascript)의 함수 중에는 객체(Object) 배열을 정렬할 수 있는 sort() 함수가 있습니다. sort() 함수는 배열의 요소를 적절한 위치에 지정한 뒤에

redcow77.tistory.com

기본 정렬을 하면 오름차순이라 내림차순으로 변경하기 위해 reverse를 써주었다.

 

sort() 쓰는 방법

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);

// [1, 2, 3, 4, 5]

 

 

axios url에 조건을 넣은 모습

"http://localhost:3001/comment?_sort=time&_order=asc"

axios에서 데이터를 받아오기 전에 state가 바로 변경되지가 않기 때문에 새로고침 전에는 역시나 댓글이 최신순으로 붙지 않았다.

시도1. 처음에는 extrareducer에서 sort, reverse로  state를 변경해주었다. 그런데 제대로 작동하지 않았다.  

 

시도2. useSelector를 이용해서 데이터 불러오고 filter하고 map을 이용해서 return할 때. sort, reverse를 써주었다. 제대로 작동했다.

 {comment
          .filter((item) => item.boardId === param)
          .map((item) => {
            return <CommentItem key={item.id} comment={item} />;
          })
          .sort((a, b) => a.time - b.time)
          .reverse()}

 

현재 날짜, 시간 가져오기 new Date()  toLocaleString()

https://programmers-sosin.tistory.com/entry/JavaScript-Date-%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EB%82%A0%EC%A7%9C-%EC%8B%9C%EA%B0%84-Date-%EA%B0%9D%EC%B2%B4

 

JavaScript Date / 자바스크립트 날짜, 시간 / Date 객체

자바스크립트 날짜와 시간 Date 객체 자바스크립트는 거의 모든 것이 객체로 이루어져 있는데 그중 날짜 기능을 가진 내장 객체 Date를 알아보겠습니다! Date 객체 생성 [ 현재 시간 ] let today = new Dat

programmers-sosin.tistory.com

 

 const newComment = {
      boardId: param,
      id: uuidv4(),
      user: user,
      pw: pw,
      content: content,
      time: new Date().toLocaleString(),
    };

 

new Date() 만 넣으면 UTC 시간이 불러와서 내가 사는 곳의 시간을 불러오려면 toLocaleString()을 붙여야한다.