[JavaScript] React-mock data

손종일·2020년 9월 15일
0

React

목록 보기
11/22
post-thumbnail

React

mock data

  • mock은 가짜의 라는 뜻을 가지고 있습니다.
  • 즉, mock data는 가짜 데이터, 샘플 데이터라고 생각하면 됩니다.
  • 실제 API 에서 받아온 데이터가 아니라 프론트엔드 개발자가 필요에 의해 직접 만들어본 데이터를 말합니다.

mock data가 필요한 이유

  • 백엔드에서 아직 API가 구현되지 않았을 때.
    (프로젝트 진행 시 레이아웃이 먼저 구현되는 경우가 많은데, 백엔드에서 API가 나올때까지 기다리는게 아니라 mock data를 만들어 데이터가 들어오는 상황을 미리 대비하고 UI가 기획에 맞게 구현되는지 확인합니다.)
  • 개발단계에서 백엔드와의 소통이 효율적으로 이루어질 수 있습니다.

mock data 관리하는 방법 2가지.

1. data.js

  • 아래와 같이 CommentData.js 를 생성하여 import해서 직접 데이터를 state에 적용하여 사용합니다.
// <CommetData.js>
const CommetData = [
  {
    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 CommetData;
import React, { Component } from 'react';
import CommentList from './CommentList/CommentList';
import CommetData from './commentData';
import './Comment.scss';

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

  componentDidMount() {
    this.setState({
      commentList: CommetData
    });
  }

  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 주소로 들어가 확인해볼 수 있습니다.

  • 해당 주소를 API 주소로 생각하고 fetch 함수와 http GET 메소드를 사용해 실제 API에서 데이터를 받아온다고 생각하고 코드를 작성해서 확인합니다.

  • fetch 함수를 통하여 GET으로 데이터를 받아와 state에 저장하여 사용합니다.

  • fetch 함수에 대해서는 다음 블로그에 자세히 다루도록 하겠습니다!

// <CommetData.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
    }
  ]
}
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;
profile
Allday

0개의 댓글