TIL 87 l Mock Data와 fetch함수

YB.J·2021년 11월 1일
0

React

목록 보기
4/4
post-thumbnail

Mock Data와 componentDidMount() 메서드, fetch함수에 대해서 적어보자

Westagram self-project 과제

Mission 1) mock data를 활용하여 여러 개의 댓글 구현

  • 댓글 데이터를 파일로 분리해서 관리해주세요.
  • 아직 fetch 함수가 익숙지 않은 분들은 .json 파일이 아닌 .js 파일로 데이터를 관리해주세요.
  • 데이터가 기획에 맞게 UI 에 나타나면 과제 완료입니다.
  • 로그인 실습 후에는 반드시 .json 파일로 변환 후 fetch 함수 적용해서 구현해주세요.

❗ Mock data란?

  • 실제 API에서 받아온 데이터가 아닌 가짜로 만든 샘플 데이터
  • mock data를 만들어 데이터가 들어오는 상황을 대비하고 UI 가 기획에 맞게 구현 되는지 확인하면 추후에 통신 오류를 줄일 수 있다
  • Backend와 주고 받는 데이터의 key-value 값을 확인하고 만드는 것이 중요하다

❗ 작성한 코드

✨ mock data로 사용될 json 파일을 관리하는 방법
public 폴더 > data 폴더 > commentData.json

✨ commentData.json

[
  {
    "id": 1,
    "userName": "jyb_1111",
    "talks": "예쁘네요"
  },
  {
    "id": 2,
    "userName": "jdh_2222",
    "talks": "멋집니다"
  },
  {
    "id": 3,
    "userName": "kws_3333",
    "talks": "WoW!!!"
  }
]

✨ 연결 : componentDidMount() 메서드와 fetch함수

  • componentDidMount() 메서드 :

    • 같은 값이 반복되지 않도록 하기 위한 메서드이다

      componentDidMount() : "최초에 한번만 작동하라"는 기능의 메서드. componentDidMount()는 component 안에서 한 번만 사용 가능하다.

    • 값을 호출해서 state에 저장하면 계속해서 render가 작동되기 때문에 componentDidMount() 메서드를 사용한다.
    • 메서드 안에 fetch() 함수를 넣으면 함수 안의 내용이 한 번만 작동된다.
  • fetch함수

  • 작성코드
class Feeds extends Component {
  constructor() {
    super();
    this.state = {
      newComment: '',
      comments: [],
      commentList: [],
      feedList: [],
    };
  }
}

  componentDidMount() {
    fetch('http://localhost:3000/data/younbeejee/commentData.json')
      .then(res => res.json())
      .then(res => {
        console.log(res);
        this.setState({
          commentList: res,
        });
        console.log(this.state.commentList);
      });
  }

render() {
    return (
      <div className="feeds">
          <article className="container">
            <div className="line">
              <img
                className="me"
                alt="me_01"
                src="https://media.istockphoto.com/photos/beautiful-woman-with-colors-smeared-on-her-face-picture-id1277619606?s=612x612"
              />
              <span className="text1">
                <b>jyb0924</b>
              </span>
            </div>

            <div className="photo">
              <img className="main_img" alt="main_image" src="https://media.istockphoto.com/photos/woman-standing-on-the-stairs-picture-id873375304?k=20&m=873375304&s=612x612&w=0&h=RxgCX3B5F1YyKj3usV6oDD8NsIUBX7XBLvAi3AGKSvE=" />
            </div>
              </div>
            </div>

            <div className="heart_line">
              <img className="heart_lne" alt="33dung" src={el.feedsPhoto} />
              <div className="text2">33dung님 외 100명이 좋아합니다</div>
            </div>

            <div className="many_lines">
              <ul className="items">
                <Child commentList={this.state.commentList} />
                {this.state.comments.map(el => (
                  <li className="item">
                    <span className="itemText">{USER_NAME}</span>
                    {el.text}
                  </li>
                ))}
              </ul>
            </div>

            <hr />

            <div className="comment">
              <input
                className="input"
                type="text"
                placeholder="댓글 달기..."
                onChange={this.textChange}
                onKeyPress={this.pressEnter}
                value={this.state.newComment}
              />
              <button className="itemAdd" onClick={this.add}>
                <a href="javascript:void(0)">게시</a>
              </button>
            </div>
          </article>
      </div>
    );
  }
}

export default Feeds;

const USER_NAME = 'jyb0924 ';
    
        
profile
♪(^∇^*) 워-후!!(^∀^*)ノシ

0개의 댓글