Wecode TIL - mock data

Younggwang Kim·2020년 12월 10일
0

Wecode

목록 보기
14/28

mock data란?

이름그대로 가짜 데이터이다. 즉, 실제 API에서 받아온 데이터가 아닌 개발자가 필요에 의해 샘플로 만는 데이터를 말한다.

목데이터가 필요한 이유?
프로젝트 진행 시 API가 나오기 이전에 페이지 레이아웃이 먼저 나오는 경우가 많다. 이럴때 백엔드의 API가 나올때까지 무작정 기다리는게 아니라, mock data를 만들어 데이터가 들어오는 상황을 가상화하여, UI가 기획에 맞게 구현되는지 먼저 확인해야 한다.
또한, 백엔드와의 소통이 효율적으로 이루어 질 수 있다. 주로 받는 데이터가 어떤 형태인지, key-value 값을 미리 맞춰볼 수 있다.

mock data 관리하는 방법

1. data.js

  • 첫번째 방법은 .js파일로 데이터를 분리하는 법이다. 배열 데이터를 변수에 담고 필요한 컴포넌트에서 import해서 사용한다.

  • .js파일은 데이터를 import하는 컴포넌트 바로 옆 접근하기 쉬운 곳에 생성한다.

    data.js
    const COMMENT = [
      {
        id: 1,
        userName: 'wecode',
        content: 'Welcome to world best coding bootcamp!',
        isLiked: true
      },
      {
        id: 2,
        userName: 'joonsikyang',
        content: 'Hi there.',
        isLiked: false
      },
      {
        id: 3,
        userName: 'jayPark',
        content: 'Hey.',
        isLiked: false
      }
    ];
    export default COMMENT;
  • Comment.js

    import React, { Component } from 'react';
    import CommentList from './CommentList/CommentList';
    import COMMENT from './commentData';
    import './Comment.scss';
    class Comment extends Component {
      constructor() {
        super();
        this.state = {
          commentList: [],
          commentValue: ''
        };
      }
    
      componentDidMount() {
        this.setState({
          commentList: COMMENT
        });
      }
    
      handleCommentValue = e => {
        this.setState({
          commentValue: e.target.value
        });
      };
    
    	addComment = e => {
        e.preventDefault();
        const { commentList, commentValue } = this.state;
        this.setState({
          commentList: [
            ...commentList,
            {
              id: commentList.length + 1,
              userName: 'wecode',
              content: commentValue,
              isLiked: false
            }
          ],
          commentValue: ''
        });
      };
    
    render() {
        const { commentList, commentValue } = this.state;
    
        return (
          <div className="comment">
            <h1>Main Page</h1>
            <ul>
              {commentList.map(comment => {
                return (
                  <CommentList
                    clickEvent={this.changeColor}
                    name={comment.userName}
                    comment={comment.content}
                  />
                );
              })}
            </ul>
            <div className="commentInput">
              <form onSubmit={this.addComment}>
                <input
                  onChange={this.handleCommentValue}
                  type="text"
                  placeholder="enter comment"
                  value={commentValue}
                />
              </form>
              <button className="addCommentBtn" onClick={this.addComment}>
                Click
              </button>
            </div>
          </div>
        );
      }
    }
    
    export default Comment;



2. data.json

  • 두 번째는 실제 API에서 보내주는 데이터 형식에 맞게 json파일에 데이터를 담아 fetch함수를 사용해 데이터를 받아오는 방법이다.
  • data.json의 위치 - public - data - data.json
  • 해당 데이터는 http://localhost:3000/data/data.json 주소를 입력하여 확인할 수 있다.



* data.json
{
  "data": [
    {
      "id": 1,
      "userName": "wecode",
      "content": "Welcome to world best coding bootcamp!",
      "isLiked": true
    },
    {
      "id": 2,
      "userName": "joonsikyang",
      "content": "Hi there.",
      "isLiked": false
    },
    {
      "id": 3,
      "userName": "jayPark",
      "content": "Hey.",
      "isLiked": false
    }
  ]
}

*해당 데이터는 http://localhost:3000/data/data.json 주소를 입력하여 확인해볼 수 있다.


*App.js

import React, { Component } from 'react';
import CommentList from './CommentList/CommentList';
import './Comment.scss';

class Comment extends Component {
  constructor() {
    super();
    this.state = {
      commentList: [],
      commentValue: ''
    };
  }

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

 render() {
    const { commentList, commentValue } = this.state;

    return (
      <div className="comment">
        <h1>Main Page</h1>
        <ul>
          {commentList.map(comment => {
            return (
              <CommentList
                clickEvent={this.changeColor}
                name={comment.userName}
                comment={comment.content}
              />
            );
          })}
        </ul>
        <div className="commentInput">
          <form onSubmit={this.addComment}>
            <input
              onChange={this.handleCommentValue}
              type="text"
              placeholder="enter comment"
              value={commentValue}
            />
          </form>
          <button className="addCommentBtn" onClick={this.addComment}>
            Click
          </button>
        </div>
      </div>
    );
  }
}

export default Comment;

목데이터에 대해서 공부중인데

0개의 댓글